linux文本处理 sort,grep,sed,awk,uniq 用法

zongan1225 8年前

来自: http://blog.csdn.net//wgw335363240/article/details/45720537


一、sort

Usage: sort [OPTION]... [FILE]...
-o 输出文件
-d 按字典顺序排序
-n 按数据大小输出
-r 按逆序输出排序结果
-k 指定分类是域上的数字分类
-t 域分隔符,用非空格或tab分隔域

sort -k3 -n -r -t: /etc/passwd
sort -d /etc/passwd

二、WC

Usage: wc [OPTION]... [FILE]...
-c 字符数量~
-l 行数~
-w 统计单词数量~
wc /etc/passwd
36 
  65 1739/etc/passwd #36行,65个单词(空格区分),1739个字符

三、diff

diff
Usage: diff [OPTION]... FILES
Compare files line by line.
-q 显示有无差异,不显示详细的信息~
-c 显示全部内文,并标出不同之处~
-b 不检查空格字符的不同~
-B 不检查空白行
-r 比较子目录中的文件~
diff /etc/passwd./passwd.bak 
 
2d1
< bin:x:1:1:bin:/bin:/sbin/nologin

四、grep
Usage: grep [OPTION]... PATTERN [FILE] ...
Search for PATTERN in each FILE or standard input.
-c 只打印匹配的行编号数
-i 匹配文本时忽略大小写
-n 在每行前显示其行编号
-v 逆向输出,打印不匹配的行
-f file 要匹配的字符在文件列表中
cat /etc/passwd |grep -n root
1:root:x:0:0:root:/root:/bin/bash
12:operator:x:11:0:operator:/root:/sbin/nologin
#grep '[Tt]his' file.txt
#grep '^[^#]' file.txt
匹配任意字符
grep 'r..t' /etc/passwd
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin
ftp:x:14:50:FTP User:/var/ftp:/sbin/nologin

五、sed

sed
Usage: sed [OPTION]... {script-only-if-no-other-script}[input-file]...
S 替代操作
i 插入命令
a 附加命令
d 删除全部匹配行
D 删除首次匹配的行

#sed -n '1,4p' /etc/passwd打印1~4行,-n --quiet以免先打印出passwd的全部内容
#sed '/80/D' file.txt
#sed 's/var/usr/g' file.txt 替换file.txt中全部var为usr
#sed '50,$s/help/man/g' file.txt 从50~最后行替换help为man
sed '/done/d' xj_user_p.log 删除done

六、awk

Usage: awk [POSIX or GNU style options] -f progfile [--] file...
Usage: awk [POSIX or GNU style options] [--] 'program' file...
 
      gawk '{ sum += $1 }; END { print sum }' file
 
      gawk -F: '{ print $1 }' /etc/passwd
NF 当前记录中的字段数。NR 当前记录数。


 
      
awk -F: '{print NR,$1,$NF}' ./passwd.bak
awk -F: 'NR==5{print NR,$0}' ./passwd.bak 打印出5,15,25...行
5 sync:x:5:0:sync:/sbin:/bin/sync
15 nobody:x:99:99:Nobody:/:/sbin/nologin
25 apache:x:48:48:Apache:/var/www:/sbin/nologin

 

七、uniq

如果要在文件中查找重复的行,uniq命令会很有用,该命令一般格式为:uniq in_fileout_file

该格式中,uniq把in_file复制到out_file,处理过程中,去掉其中的重复行,uniq对重复行的定义是完全匹配的连续行。如果不指定out_file,结果就写入标准输出。
-d选项:它告诉uniq把文件中的重复行写入out_file,不管它们在文件中连续出现多少次,这样的连续行只写一次
-c选项:带-c选项后,每行最前面显示该行在输入文件中出现的次数。

$ more test.txt
aaa
ccc
ccc
ccc
ddd
bbb
eee
123
$ uniq test.txt
aaa
ccc
ddd
bbb
eee
123
$ uniq -d test.txt
ccc
$ uniq -c test.txt
 
  1 aaa
 
  3 ccc
 
  1 ddd
 
  1 bbb
 
  1 eee
 
  1 123
$

综合示例:

...
数据处理:
找出上海股票涨幅最大的股票?
sort -n -r -k4 t.txt | sed -n '1p'
涨幅>3的股票?
awk '{if ($1>3) print $0} ' t.txt
涨幅在在4~15之间的股票
awk'{if($4>0&&$4<15){print$0}}' t.txt

 

转自:http://hi.baidu.com/��������/blog/item/caf21ba89c54ada1ca130c4a.html

http://hi.baidu.com/edeed/blog/item/b1be513db16db5ed3c6d9727.html

</div>