目标:
替换linux文件中的一行内容为其他的内容。
这分为几种情况:
-
整行替换
-
部分替换
-
替换为固定内容
-
替换为匹配内容
-
替换为变量
整行替换
先搞个文件出来
for i in {a..e};do echo $i >> test.txt;done
cat test.txt
a
b
c
d
e
把第一行换成hello world
sed '1s/.*/hello world/' test.txt > test1.txt
sed ‘1,3s/.*/hello/’ test.txt > test1.txt
也可以多行执行同一个命令。自带循环。
行部分替换
只需要修改正则表达式就行
sed '1s/world/meinv/' test1.txt > test2.txt
替换为固定内容
只需要给定固定替换内容就行。
比如上例子。
替换为匹配内容
其实就是反向匹配。
我们现在需要把字母的行变成两倍比如a换成aa。
补充内容sed查看行号。比awk稍微复杂一点。
sed "=" test2.txt
1
hello meinv
2
b
3
c
4
d
5
e
sed = test1.txt | sed 'N;s/\n/\t/'
1 hello world
2 b
3 c
4 d
5 e
sed -r 's/^([a-z])$/\1\1/' test2.txt > test3.txt
hello meinv
bb
cc
dd
ee
\1就是反向匹配
cool!
替换为变量
a="hello wang"
sed "1s/.*/$a/" test3.txt > test4.txt
唯一需要注意的是要用双引号。
不然变量会当做模式字符串。这一点区别于以上的所有例子
!!!