sed命令是linux中的常用命令,主要作用是文本文件、字符串处理。平时在使用sed的时候会有在使用s字符串替换的时候遇到或者用到使用&符号,这里对&符号的作用做简单的说明。
&符号的作用是在使用s字符串替换的时候代替匹配的字符串的作用,下面举个例子来解释
[root@localhost:~]# cat > test.txt << EOF
I have a pen
I have an apple
pen and apple
EOF
[root@localhost:~]# sed 's/pen/other &/g' test.txt # 不加-i不会修改文件内容
I have a other pen
I have an apple
other pen and apple
[root@localhost:~]# sed 's/^pen/I have &/g' test.txt # 不加-i不会修改文件内容
I have a pen
I have an apple
I have pen and apple
[root@localhost:~]# sed 's/I have.*/&, add string./g' test.txt # 不加-i不会修改文件内容
I have a pen, add string.
I have an apple, add string.
pen and apple
从上面操作可以看出来 &符号代表匹配到需要替换的字符串,更进一步可以用这种方式来实现a(行下追加)和i(行上追加)的效果,具体操作可参考如下
[root@localhost:~]# sed 's/I have an.*/&\nadd a line/g' test.txt # 实现行下追加
I have a pen
I have an apple
add a line
pen and apple
[root@localhost:~]# sed 's/I have an.*/add a line\n&/g' test.txt # 实现行上追加
I have a pen
add a line
I have an apple
pen and apple