sed用法总结
用法: sed -【Options】 ‘AddressCommand’ file
Options基本命令:
- -n : 只有经过sed特殊处理的哪一行才会被列出来
- -i :直接在原文件做修改
- -r : 使用正则表达式,不需要做转义
- -e :前面执行完,传送给后面
- -f :跟随sed脚本文件名
Address用法:
- startLine,emdLine (1,100)
- /regeXP/ (^root)
- /pattern1/,/pattern2/ (第一次被匹配到pattern1的行开始到第一次匹配到pattern2的行结束)
- startLine,+N (从startLine开始,向后N行)
- lineNum (指定的行)
Command命令用法:
- d : 删除符合条件的行
- p : 显示符合条件的行
- a"string" : 在指定的行之后追加新行,内容为string (另起一行)
- i"string" : 在指定的行之前追加新行,内容为string (另起一行)
- c"string" : 替换当前行内容为string
- w file: 将指定范围的内容输出到新的文件中
- s/pattern/string/g :查找并替换
- n : 读取下一个输入行, 用下一个命令处理新的行
例子:
删除:
sed '2d' test.txt 删除文件第2行
sed '2,3d' test.txt 删除文件第2到3行
sed '2,$d' test.txt 删除文件第2行到最后一行
sed ' $d' test.txt 删除文件最后一行
sed 'd' test.txt 删除文件所有行
sed '/abc/d' test.txt 删除文件中包含字符串abc所有的行
sed '2,5d' test.txt 删除文件中第2行到第5行
替换
sed 's/1111/2222/g' test.txt 在整行范围内,将1111替换为2222
sed -n s/^1111/2222/p test.txt 只打印发生替换的行,行首为1111的被替换打印
sed ‘s/^192.168.1.1/&localhost’ file &符号表示替换字符串中被找到的部分.,变成192.168.1.1localhost
sed -n ‘s/\(love\)able/\1rs/p’ file love被标记为1,所有loveable会被替换成lovers,而且替换的行会被打印出来
sed ‘s#10#100#g’ file 不论什么字符,紧跟着s的命令都被认为是最新的分隔符
选定行的范围: 逗号
sed -n ‘/test/,/check/p’ file 所有在模块test和check所确定范围内的行都被打印
sed -n ‘5,/^test/p’ file 打印从第5行开始到第一个包含以test开始行之间的所有行
sed ‘/test/,/check/s/$/sed test/’ file 对于模块test和west之间的行,每行的末尾用字符串sed test替换
多点编辑: e命令
sed -e ‘1,5d’ -e ‘s/test/check/’ file -e选项允许在同一行里执行多条命令.删除1-5行,check替换test
sed -e ‘/and/s/aaa/bbb’ file sed中用bbb替换同一行中包括字符串and的字符串aaa,而不是每一行中的字符串aaa
sed ‘/test/r file_a’ file file_a里的内容被读进来,显示在与test匹配的行后面. 如果匹配多行,则file_a内容将显示在所有匹配行的下面
//写入文件: w命令
sed -n ‘test/w file_a’ file file中所包含的test行都被写入file里
//插入: i命令
sed ‘/test/i\\ new line’ file 如果test被匹配, 则把反斜杠后面的文本插入到匹配行的上面
sed -e ‘1 ia’ -e ‘$ a3′ file 在第一行上面插入a,在末尾行下面插入3
//下一个: n命令
sed ‘/test/{n; s/aa/bb/;}; file 如果test被匹配, 则移动到匹配行的下一行,替换这一行的aa变为bb, 并打印该行,然后继续