Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading