• Uncategorized

About linux : How-to-append-or-prepend-a-path-string-in-a-text-file-using-sed

Question Detail

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


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


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?

Question Answer

Use sed’s pattern space and hold space:

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



See: man sed

You can try like this

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

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.