目录:
1. 打印。。 http://www.thegeekstuff.com/2009/09/unix-sed-tutorial-printing-file-lines-using-address-and-patterns/
Syntax:# sed -n 'ADDRESS'p filename# sed -n '/PATTERN/p' filename
2.删除
http://www.thegeekstuff.com/2009/09/unix-sed-tutorial-delete-file-lines-using-address-and-patterns/Syntax:# sed 'ADDRESS'd filename# sed /PATTERN/d filename3.查找替换 http://www.thegeekstuff.com/2009/09/unix-sed-tutorial-replace-text-inside-a-file-using-substitute-command/
#sed 'ADDRESSs/REGEXP/REPLACEMENT/FLAGS' filename#sed 'PATTERNs/REGEXP/REPLACEMENT/FLAGS' filename学到了如何将windows下的换行批量转unix
sed 's/.$//' filename这个.号也可以显示地写成\r,因为每行在处理之前会先自动去掉\n所以每行的最后一个字符是\r 4. 写文件 http://www.thegeekstuff.com/2009/10/unix-sed-tutorial-how-to-write-to-a-file-using-sed/
#sed 'ADDERSSw outputfile' inputfilename#sed '/PATTERN/w outputfile' inputfilename
学到了同时执行多段脚本:
sed -n -e '1w output.txt' -e '$w output.txt' thegeekstuff.txt
5。如何执行多个sed command
http://www.thegeekstuff.com/2009/10/unix-sed-tutorial-how-to-execute-multiple-sed-commands/Syntax:#sed -e 'command' -e 'command' filename如果只有一个command则-e可写可不写。(难怪) 删除第一行, 最后一行和空白行
sed -e '1d' -e '$d' -e '/^$/d' thegeekstuff.txt
6.高级替换
6-1如果REGEX或REPLACEMENT中有/,则需要用\转义,或者使用@ % | ; : 做为sed的分隔符sed 's@/opt/omni/lbin@/opt/tools/bin@g' path.txt以上用@做为分隔符替换某个路径值
6-2 &用在REPLACEMENT指代REGEX实际匹配的那部分内容
sed 's@/usr/bin@&/local@g' path.txt这里的&指代/usr/bin, 又比如
sed 's@^.*$@<<<&>>>@g' path.txt把每行用<<<>>>括起来。。这个用法比较实用 6-3分组和back refercence A group is opened with “\(” and closed with “\)”, 并且back reference即可用在REGEX部分也可以用在replacement部分
sed 's/\(\/[^:]*\).*/\1/g' path.txt每行只保留第一个冒号前面的路径 ==> /usr/kbos/bin:/usr/local/bin:/usr/jbin/ 变成 /usr/kbos/bin
又比如:
$ sed '$s@\([^:]*\):\([^:]*\):\([^:]*\)@\3:\2:\1@g' path.txt颠倒最后一行3个路径的出现顺序,
又比如
sed 's/\([^:]*\).*/\1/' /etc/passwd从/etc/passwd中取所有的用记名(第一列就是) 又比如
$ echo "Welcome To The Geek Stuff" | sed 's/\(\b[A-Z]\)/\(\1\)/g'(W)elcome (T)o (T)he (G)eek (S)tuff将每个单词首字母用括号括起来,我试了一下,这个例子中replacement部分括号是不需要转义的 这样也行 ==> echo "Welcome To The Geek Stuff" | sed 's/\(\b[A-Z]\)/(\1)/g' 7. 插入行, 替换行, 打印行号 http://www.thegeekstuff.com/2009/11/unix-sed-tutorial-append-insert-replace-and-count-file-lines/#count_lines
Syntax:#sed 'ADDRESS a\ Line which you want to append' filename#sed '/PATTERN/ a\ Line which you want to append' filename在上面的syntax中, a表示在某行之后插入, 之前用i, 替换用c 比如我有一个文件hello.sh内容如下: echo "hello cyper" 使用后插a,前插i,和替换c之后的效果如下:
$ sed '1 a#!/bin/sh' hello.shecho "hello cyper"#!/bin/sh$ sed '1 i#!/bin/sh' hello.sh#!/bin/shecho "hello cyper"$ sed '1 c#!/bin/sh' hello.sh#!/bin/sh$
当然我的本意是前插, 所以在这种情况下选择i
8. 同时操作多行 (待读)
http://www.thegeekstuff.com/2009/11/unix-sed-tutorial-multi-line-file-operation-with-6-practical-examples/ 9. http://www.thegeekstuff.com/2009/12/unix-sed-tutorial-7-examples-for-sed-hold-and-pattern-buffer-operations/10.http://www.thegeekstuff.com/2009/12/unix-sed-tutorial-6-examples-for-sed-branching-operation/