linux命令sed
语法结构:
sed[addr][options]
具体看man sed
使用后如果不用w filename保存,则只是显示结果在终端,不会改变源文件内容
w 标记会将匹配后的结果保存到指定文件中,比如:
[root@localhost ~]# sed 's/test/trial/w test.txt' data2.txt
This is a trial line.
This is a different line.
[root@localhost ~]#cat test.txt
This is a trial line.
sed pattern表达式
action表达式
p打印
s查找替换:s/REGEXP/REPLACEMENT <--常用
d删除,删除前两行sed'1.2d'
#d删除,删除前两行sed'1.2d'
manshuo@Dashuo:~/temp$ cat sort 60MB 10 1000KB 20MB 300KB 5 3 A G 40GB 50KB manshuo@Dashuo:~/temp$ sed '1,2d' sort 1000KB 20MB 300KB 5 3 A G 40GB 50KB
行数操作:
删除array里面最后一行:sed '$d' array
替换:sed 's/a/great_a/' array
将array文件里面的a替换成great_a
#将sort文件里面的sort替换成change sort
manshuo@Dashuo:~/temp$ cat sort 60MB 10 1000KB 20MB 300KB 5 3 A G 40GB 50KB sort manshuo@Dashuo:~/temp$ sed 's/sort/change sort/' sort 60MB 10 1000KB 20MB 300KB 5 3 A G 40GB 50KB change sort
s表达式:
s表示替换
s后面的追加字符以为任意字符
g表示全局匹配 eg:sed 's#1#9#g' -->把所有1替换成9,默认是只替换当行的第一个匹配项
&表示匹配内容 eg:
echo 1:2:3 | sed 's/:/adb&/' -->在冒号前加入adb,加g可全局替换
manshuo@Dashuo:~/temp$ cat sed_demo
test test
test test2
test test3
i am a happy man
test test
happy
123
23
manshuo@Dashuo:~/temp$ sed 's/test/demo/' sed_demo #没用g,一行中的test只替换第一个
demo test
demo test2
demo test3
i am a happy man
demo test
happy
123
23
manshuo@Dashuo:~/temp$ sed 's/test/demo/g' sed_demo #用g,一行中的test全部被替换
demo demo
demo demo2
demo demo3
i am a happy man
demo demo
happy
123
23
manshuo@Dashuo:~/temp$ cat sed_demo
test
test2
test3
i am a happy man
test
happy
123
23
manshuo@Dashuo:~/temp$ sed 's/test/it is a &/' sed_demo #追加信息
it is a test
it is a test2
it is a test3
i am a happy man
it is a test
happy
123
23
反向引用
echo 0 1 2 3 4 | sed -E 's#([1-3]) ([1-3]) ([1-3])#\3 \2 \1#'
输出:
0 3 2 1 4
([1-3]) ([1-3]) ([1-3]) :匹配1~3 的三个字符,一个括号一位
\3 代表第三个匹配数
manshuo@Dashuo:~/temp$ sed -E 's#([1-3])([1-3])([1-3])#\3 \2 \1#' sed_demo test test test test2 test test3 i am a happy man test test happy 3 2 1 23