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

Time:12-31

Say I have a text file, namely, files.txt. And in files.txt I have a list of paths, for instance:

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

I want to be able to move one line to another line, for instance:

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

I have tried to use these commands to do that. The first one works. But the second one doesn't work because of the forward slash:

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

I have tried using temporary variable with single quotes to indicate literal string but it still won't work (it is actually to be used using variable). Also I have tried using an arbitrary character to replace the forward slash because sed doesn't care in some cases but it's different this time. How I might be able to achieve that using sed?

CodePudding user response:

Use sed's pattern space and hold space:

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

Output:

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

See: man sed

CodePudding user response:

You can try like this

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