Search This Blog


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 ''

No comments:

Post a Comment