Linux 字符处理命令



排序-sort


sort [选项] [文件]
什么都不加,默认按照首字母排序,默认以空格为分隔符。

-t		指定分隔符,默认使用空格为分隔符。
-k		指定第几列。
[root@oldboy ~]# cat sort.log |sort -t'.' -k2
218.65.30.124 17163
218.65.30.126 17163
218.65.30.25 68652
218.65.30.53 34326
218.65.30.61 17163
112.85.42.103 18065
112.85.42.99 17164
218.87.109.150 17163
218.87.109.151 17163
218.87.109.154 21201

-n		按照阿拉伯数字排序,默认按照字母的首个字符排序。
-r		反转
[root@oldboy ~]# cat sort.log |sort -t' ' -k2 -nr
218.65.30.25 68652
218.65.30.53 34326
218.87.109.154 21201
112.85.42.103 18065
112.85.42.99 17164
218.87.109.151 17163
218.87.109.150 17163
218.65.30.61 17163
218.65.30.126 17163
218.65.30.124 17163


去重-uniq


uniq 选项 文件
作用:去重,只能把相邻的相同的内容去重。
-c		统计

[root@oldboy ~]# cat sort1.txt |sort|uniq -c
      2 192.168.0.151
      1 192.168.0.152
      2 192.168.0.153
      1 192.168.1.1
      1 192.168.1.10
      1 192.168.1.11



截取字符-cut


用法: cut [选项] [文件]

-d		指定分隔符
-f		指定区域
[root@oldboy ~]# cut -d':' -f1,7 /etc/passwd
root:/bin/bash
bin:/sbin/nologin
daemon:/sbin/nologin
adm:/sbin/nologin

-c		取字符
[root@oldboy ~]# echo 123456 |cut -c 3-5
345

字符替换-tr


tr 旧字符 新字符
[root@oldboy ~]# echo 123a123b123c|tr 'a' 'b'
123b123b123c

统计命令-wc


wc 文件
[root@oldboy tmp]# wc /etc/services 
 11176  61033 670293 /etc/services

-c			按照字节数统计
[root@oldboy ~]# wc -c /etc/services 
670293 /etc/services

-w			按照单词数统计
[root@oldboy ~]# wc -w /etc/services 
61033 /etc/services

-l			统计行数
[root@oldboy ~]# wc -l /etc/services 
11176 /etc/services

原文地址:https://www.cnblogs.com/gshelldon/p/13269698.html