sed学习总结
sed学习总结
sed工作流
测试文件:cat employee.txt
101,John Doe,CEO
102,Jason Smith,IT Manager
103,Raj Reddy,Sysadmin
104,Anand Ram,Developer
105,Jane Miller,Sales Manager
sed命令语法
sed [options] {sed-commands} {input-file} (单条命令)
sed [options] -f {sed-commands-in-a-file} {input-file} (脚本文件)
sed [options] -e {sed-command-1} -e {sed-command-2} {input-file} (多条命令)
sed打印输出
sed -n 'p' employee.txt
101,John Doe,CEO
102,Jason Smith,IT Manager
103,Raj Reddy,Sysadmin
104,Anand Ram,Developer
105,Jane Miller,Sales Manager
sed 'p' employee.txt
101,John Doe,CEO
101,John Doe,CEO
102,Jason Smith,IT Manager
102,Jason Smith,IT Manager
103,Raj Reddy,Sysadmin
103,Raj Reddy,Sysadmin
104,Anand Ram,Developer
104,Anand Ram,Developer
105,Jane Miller,Sales Manager
105,Jane Miller,Sales Manager
sed -n '2 p' employee.txt 仅输出第2行
sed -n '1,4 p' employee.txt 输出1到4行
sed -n '2,$ p' employee.txt 输出2到最后一行
匹配行
sed -n '1~2 p' employee.txt
101,John Doe,CEO
103,Raj Reddy,Sysadmin
105,Jane Miller,Sales Manager
1~2 匹配1,3,5,7……奇数行
2~2 匹配2,4,6,8……偶数行
1~2 匹配1,4,7,10……
1~2 匹配2,5,8,11……
模式输出
sed -n '/Jane/ p' employee.txt 输出与Jane匹配的行
sed -n '/Jason/,4 p' employee.txt 输出从第一个匹配Jason的行到第4行
sed -n '/Raj/,$ p' employee.txt 输出第一个匹配Raj的行到最后一行
sed -n '/Raj/,/Jane/ p' employee.txt 输出匹配Raj的行到匹配Jane的行
sed -n '/Jason/,+2 p' employee.txt 输出匹配Jason的行再输出之后两行
删除行(仅影响输出不作源文件修改)
sed '2 d' employee.txt 删除第2行
sed '1,4 d' employee.txt 删除1到4行
sed '2,$ d' employee.txt 删除2到最后一行
sed '1~2 d' employee.txt 删除奇数行
sed '/Manager/ d' employee.txt 删除匹配Manager的行
sed '/Jason/,4 d' employee.txt 删除匹配Jason的行到第4行
sed '/Raj/,$ d' employee.txt 删除匹配Raj的行到最后一行
sed '/Raj/,/Jane/ d' employee.txt 删除匹配Raj的行知道匹配Jane的行
sed '/Jason/,+2 d' employee.txt 删除第一个匹配Jason的行及之后两行
sed '/^$/ d' employee.txt 删除空行
sed '/^#/ d' employee.txt 删除#开头的行(注释行)
替换命令
语法
sed '[address-range|pattern-range] s/originalstring/replacement-string/[substitute-flags]' inputfile
实例
sed 's/Manager/Director/' employee.txt
sed '/Sales/s/Manager/Director/' employee.txt 在匹配Sales的行替换
sed 's/a/A/' employee.txt
sed 's/a/A/g' employee.txt 全局替换
sed 's/a/A/2' employee.txt 替换每行第2个a
sed -n 's/John/Johnny/p' employee.txt
sed 's/john/Johnny/i' employee.txt 忽略大小写
参考资料
[1]. Sed-and-Awk-101-Hacks.pdf
形而上者谓之道 形而下者谓之器。