天天看点

Linux命令学习-文本分析

命令列表

  • cut
  • short
  • wc
  • sed(行编辑器)
  • awk

cut-显示切割的行数据

[option]
-f:选择显示的列
-s:不显示没有分隔符的行
-d:自定义分隔符
           

eg01: 以空格分割显示前三列

[[email protected] ~]# cut -d' ' -f1,2,3 grep.txt
abcedfghio
abc def ghi
qwe rty
zxc
           
[[email protected] ~]# cut -d' ' -f1-3 grep.txt
abcdefghio
abc def ghi
qwe rty
zxc
           

不显示没有分隔符的行

[[email protected] ~]# cut -d' ' -s -f1-3 grep.txt
abc def ghi
qwe rty
           

sort-排序文件的行

-n:按数值排序

-r:倒序

-t:自定义分隔符

-k:选择排序列

-u:合并相同行

-f:忽略大小写

eg01: 默认是按字典顺序排序(第一个字符相同则比较第二个,仍相同则比较第三个。。。。。。)

[[email protected] ~]# sort sort.txt 
apple 1
banana 12
orange 8
pear 5
           

eg02: 逆序排序

[[email protected] ~]# sort -r sort.txt 
pear 5
orange 8
banana 12
apple 1
           

eg03: 以第二列数值顺序排序

[[email protected] ~]# sort -t' ' -n -k2 sort.txt 
apple 1
pear 5
orange 8
banana 12
           

wc-word count,字符统计

-c:统计所占字节数(包括空格,换行)

-m:统计字符个数

-w: 统计单词的个数

-l:统计行数

eg01:

[[email protected] ~]# cat sort.txt | wc
      4       8      34
[[email protected] ~]# cat sort.txt | wc -c
34
[[email protected] ~]# cat sort.txt | wc -l
4
[[email protected] ~]# cat sort.txt | wc -m
34
[[email protected] ~]# cat sort.txt | wc -w
8
[[email protected] ~]# 
           

sed-行编辑器

语法:

[option]
-n 静默模式,不再默认显示模式空间中的内容
-i 直接修改原文件
-e 同时执行多个脚本
-f 使用脚本文件
-r 表示使用扩展正则表达式

[Address]
可以没有
给定范围
查找指定行/str/

[Command]
d 删除符合条件的行;
p 显示符合条件的行;
a\string 在指定的行后面追加新行,内容为string
a\n 可以用于换行
i\string 在指定的行前面添加新行,内容为string
r FILE 将指定的文件的内容添加至符合条件的行处
w FILE 将地址指定的范围内的行另存至指定的文件中; 
s/pattern/string/修饰符: 查找并替换,默认只替换每行中第一次被模式匹配到的字符串
g 行内全局替换
i 忽略字符大小写
s///: s###, s@@@	
	\(\), \1, \2
           

eg01: 静默输出文件中第二行的信息

[[email protected] ~]# sed -n "2p" sort.txt 
pear 5
           

eg02: 输出文件除了第2行之外的信息

[[email protected] ~]# sed "2d" sort.txt 
banana 12
apple 1
orange 8
           

eg03: 修改原文件,删除文件中第二行的信息

[[email protected] ~]# sed -i "2d" sort.txt 
           

eg04: ,修改原文件,在第二行后追加新行,内容为abc

[[email protected] ~]# sed -i "2a\abc" sort.txt 
           

eg05: 修改原文件,在第二行前追加新行,内容为abc

[[email protected] ~]# sed -i "2i\abc" sort.txt 
           

eg06: 修改原文件,将apple替换成happy

[[email protected] ~]# sed -i "s/apple/happy/" sort.txt
           

eg07: 修改原文件,删除匹配到happy的那行

[[email protected] ~]# sed -i "/happy/d" sort.txt
           

eg08: 替换inittab文件“id:3:initdefault:”这一行的3替换成5

[[email protected] ~]# sed "s/\(id:\)[0-6]\(:initdefault:\)/\15\2/" inittab
           

eg09: 替换inittab文件“id:3:initdefault:”这一行的3替换成变量num的值

[[email protected] ~]# sed "s/\(id:\)[0-6]\(:initdefault:\)/\1$num\2/" inittab
           

未完待续。。。。。。

继续阅读