shell常用文件处理命令

来源:互联网 发布:2017网络音乐排行榜 编辑:程序博客网 时间:2024/05/18 01:50

文件的合并与分割:
1. sort
命令格式:
sort -cmu -o output_file [other options] +pos1 +pos2 input_file
-c 测试文件是否已经分类。
-m 合并两个分类文件。
-u 删除所有复制行。
-o 存储s o r t结果的输出文件名。
其他选项有:
-b 使用域进行分类时,忽略第一个空格。
-n 指定分类是域上的数字分类。
-t 域分隔符;用非空格或tab键分隔域。
-r 反向排序。
+n n为域号。使用此域号开始分类。[第一列为域0]
pos1 pos2 传递到m,n。m为域号,n为开始分类字符数;例如4,6意即以第5域分类,从第7个字符开始。

$ sort f1.txt
$ sort -t: f2.txt
对于数字域, 使用
$ sort +0n f1.txt          % 0表示第1个域, 可使用任何域
$ sort +2 f1.txt           % 以第3个域排序
$ sort -u f1.txt       % 排序时去除重复行

$ head -n f1.txt           % 显示文件的前n行
$ tail -n f1.txt

$ sort +0n -r f1.txt | head -1 | awk '{print "worst case", $1, "has been rented by", $2}'
worst case 483 has been rented by tfj

合并文件:
$ sort -m file1 file2

提取/etc/passwd中的用户名并排序显示:
$ sort -t: +0 /etc/passwd | awk -F: '{print $1}'

以ip地址的最后一个域排序显示:
$ sort -t. +3n iplist_file      % 文件内容为nnn.nnn.nnn.nnn XX


uniq: 删除*连续*重复出现的行
格式: uniq -udc -f input_file [output_file]
选项含义:
-u 只显示不重复行。
-d 只显示有重复数据行,每种重复行只显示其中一行
-c 打印每一重复行出现次数。
-f n为数字,前n个域被忽略。
一些系统不识别- f选项,这时替代使用- n。
$ more a.txt
May
May
May
haha
May
$ uniq a
May
haha
May

连接文件: join
需要两个文件有相同的域(类似数据库的join)

cut: 提取文件内容
c u t一般格式为:
cut [options] file1 file2
下面介绍其可用选项:
-c list 指定剪切字符数。
-f field 指定剪切域数。
-d 指定与空格和t a b键不同的域分隔符。
- c用来指定剪切范围,如下所示:
- c 1,5-7 剪切第1个字符,然后是第5到第7个字符。
-c1-50 剪切前5 0个字符。
-f 格式与- c相同。
-f 1,5 剪切第1域,第5域。
- f 1,10-12 剪切第1域,第1 0域到第1 2域。

$ more a
p.joines:office runner:id897
s.round:unix admin:id666
l.clip:personel chief:id982
$ cut -d: -f3 a
id897
id666
id982
从/etc/passwd截取用户名和使用的shell:
$ cut -d: -f1,7 /etc/passwd
root:/bin/sh
tfj:/bin/bash
....

paste: 粘贴
paste -d: f1 f2        % 两文件不必具有相同的行数
-d 指定分隔符默认空格
$ more a
tfj
zyc
$ more b
id111
id222
$ paste a b
tfj id111
zyc id222

split:分割大文件
split -N file            % N为分割后文件的行数(最大为1000)
生成的小文件以xaa,xab,xac.....xzz命名.

tr: 从stdin中通过替换或删除操作进行字符转换
tr -cds pattern-string string_to_be_manipulated

$ echo "aaaaaabbcccd" | tr -s "[a-z]"
abcd
删除空行:
$ tr -s "[/n]" < file
大写转小写:
$ cat file | tr "[A-Z]" "[a-z]"
tr的功能用sed都能实现.