简体   繁体   中英

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:

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?

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

You can try like this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM