工作中常用的Linux命令小结

CPU 占用过高

    1、top 找到相应的进程
    2、使用 top -p -H 进程Id  ----》去查看子线程中最高的
    3、使用printf "%x \n" 子线程号   ----》 去查看子线程号对应的16进制数字
    4、根据子线程的十六进制查看相关的代码 jstack 进程号|grep 子线程号16进制 -C 30

rm -rf

不要被吓到,知道原理就不会害怕了(不明觉厉)

1.统计文件的行数

nowcoder.txt 内容如下:
#include <iostream>
using namespace std;
int main()
{
    int a = 10;
    int b = 100;
    cout << "a + b:" << a + b << endl;
    return 0;
}

解:

方法1: wc -l nowcoder.txt |awk '{print $1}'
方法2: awk 'END{print NR}' nowcoder.txt

2.打印文件的最后5行

#include<iostream>
using namespace std;
int main()
{
int a = 10;
int b = 100;
cout << "a + b:" << a + b << endl;
return 0;
}

解:

tail -5 nowcoder.txt

3.输出7的倍数

解:

seq 0 7 500

4.输出第5行的内容

解:

方法1:head -5 nowcoder.txt |tail -n 1
方法2:sed -n 5p

5.打印空行的行号

解:

awk '{if($0=="") {print NR}}'  nowcoder.txt

6.去掉空行

解:

awk '{if($0!="")print $0}' nowcoder.txt

7.打印字母数小于8的单词

解:

打印每一行中 每个单词的个数小于8的用NF表示有多少列

awk '{for(i=1;i<=NF;i++)if(length($i)<8)print $i}' nowcoder.txt

8.统计所有进程占用内存大小的和
(统计第5列数子的和)

解:

统计第6列数字的和

awk '{count+=$6}END {print count}' nowcoder.txt

9.统计每个单词出现的个数

解:

awk '{for(i=1;i<=NF;i++){print $i}}' nowcoder.txt|sort|uniq -c | sort |awk '{print $2 $1}'

10.第二列是否有重复

给定一个 nowcoder.txt文件,其中有3列信息,如下实例,编写一个sheel脚本来检查文件第二列是否有重复,且有几个重复,并提取出重复的行的第二列信息:
实例:
20201001 python 99
20201002 go 80
20201002 c++ 88
20201003 php 77
20201001 go 88
20201005 shell 89
20201006 java 70
20201008 c 100
20201007 java 88
20201006 go 97

解:

awk '{print $2}' nowcoder.txt |sort |uniq -c |sort| awk '{if($1>1)print $1,$2}'

11.转置文件内容

示例:
假设 nowcoder.txt 内容如下:
job salary
c++ 13
java 14
php 12

你的脚本应当输出(以词频升序排列):
job c++ java php
salary 13 14 12

解:

awk '{for(i=1;i<=NF;i++)mp[i]=mp[i]$i}END{for(k in mp)print mp[k]}' nowcoder.txt

12.打印每一行数字出现的个数

1,2,3,4,5数字个数并且要计算一下整个文档中一共出现了几个1,2,3,4,5数字数字总数。

解:

sed s/[^1-5]//g nowcoder.txt | awk '{a+=length($1);printf("line%d number: %d\n",NR,length($1))} END{printf("sum is %d",a)}'

13.去掉所有含有this的句子

示例:
假设输入如下:
that is your bag
is this your bag?
to the degree or extent indicated.
there was a court case resulting from this incident
welcome to nowcoder


你的脚本获取以上输入应当输出:
to the degree or extent indicated.
welcome to nowcoder

解:

awk '{flag=1;for(i=1;i<=NF;i++)if($i=="this")flag=2;if(flag==1)print $0}' nowcoder.txt

14.求平均值

第1行为输入的数组长度N
第2~N行为数组的元素,如以下为:
数组长度为4,数组元素为1 2 9 8
示例:
4
1
2
9
8

那么平均值为:5.000(保留小数点后面3位)
你的脚本获取以上输入应当输出:
5.000

解:

awk '{if(NR==1)fm=$1;count+=$1}END{printf "%.3f", ((count-fm)*1.000/fm)}' nowcoder.txt

15.去掉不重复的单词

示例:
假设输入如下:
big
nowcoder
Betty
basic
test

你的脚本获取以上输入应当输出:
nowcoder test

解:

方法1:grep -iv b
方法2:sed -r '/.*[bB].*/d'