如何使用 sed 在文本文件中添加或添加路径字符串

How to append or prepend a path string in a text file using sed

假设我有一个文本文件,即files.txt。 在 files.txt 中,我有一个路径列表,例如:

/home/user/qwe
/home/user/asd
/home/user/zxc

我希望能够将一行移动到另一行,例如:

/home/user/asd
/home/user/qwe
/home/user/zxc

我已经尝试使用这些命令来做到这一点。第一个有效。但是由于正斜杠,第二个不起作用:

sed -i "2d" /home/user/files.txt
sed -i "/^'/home/user/asd'/i '/home/user/qwe/'" /home/user/files.txt

我试过使用带单引号的临时变量来指示文字字符串,但它仍然不起作用(它实际上是使用变量来使用)。我还尝试使用任意字符替换正斜杠,因为 sed 在某些情况下不关心,但这次不同。 我怎样才能使用 sed 实现这一目标?

你可以这样试试

sed -i 's|/home/user/asd|/home/user/qwe|g' /home/user/files.txt

使用 sed 的模式 space 并保持 space:

sed '1{h;d}; 2{p;x}' file

输出:

/home/user/asd
/home/user/qwe
/home/user/zxc

参见:man sed