Search This Blog

2013-04-11

Appending Text to the End of Matching Line with SED

What the following does is matches the end of each line and adds additional string to each end of line it matches.

sed -i -e '/MATCH/s/$/REPLACE/' /path/to/file

-i - replace file in-line
-e - I believe specifies the command you want to use (in this case 's' is the command which means substitute

So what we're doing above is matching the MATCH string and instead of the end-line denoted by '$' we will be replacing the end of the line with the REPLACE string

We can also use variable with sed but you need to remember to quote them to ensure they're recognized as variables and not strings or special characters as follows:
sed -i -e '/'$1'/s/$/'$2'/' 

inline replace normally requires an additional argument to specify a backup file when doing in-line editing.

If it complains then you can perform one of the following options:
  1. add an argument and it will create a backup file with the extension .bak
    sed -i '.bak'
    
  2. add a blank argument to edit in-line without a backup (which can be dangerous)
    sed -i ''
References:
http://www.theurbanpenguin.com/linux/scripts/sedappend.html
http://stackoverflow.com/questions/9591744/add-to-the-end-of-a-line-containing-a-pattern-with-sed-or-awk
http://serverfault.com/questions/72744/command-to-prepend-string-to-each-line
http://stackoverflow.com/questions/3600079/sed-match-line-and-add-word-on-the-first-string-in-line
http://stackoverflow.com/questions/1558458/appending-text-to-the-existing-first-line-with-sed

No comments:

Post a Comment