8

inputs:

line1 with the PATTERN that contains ( ) 
line2 with the PATTERN that contains ( ) 
lineN with the PATTERN that contains ( ) 

outputs:

line1 with the PATTERN that contains ( ) ;
line2 with the PATTERN that contains ( ) ;
...
lineN with the PATTERN that contains ( ) ;

I tried this:

find . -name "test.txt" -print | xargs sed -i "/PATTERN/ s/$)/); /g"

but it didn't work.

3
perl -ipe 's/$/;/ if /PATTERN/'

This will add a ; at the end if the line contains PATTERN.

| improve this answer | |
3

The $ matches the end of the line, so your pattern should be )$ instead of $) like in your example.

Also, you don't need xargs here, it's safer to use the -exec flag of fine:

find . -name test.txt -exec sed -i '/PATTERN/ s/)$/); /' '{}' +

If your version of find doesn't work with + at the end, then use \; instead (thank you @glenn-jackman):

find . -name test.txt -exec sed -i '/PATTERN/ s/)$/); /' '{}' \;

Finally, there's no need for the g flag in a s/something$// idiom, as there is only one occurrence of $ per line.

| improve this answer | |
  • 1
    You'll gain some efficiency with -exec ... + instead of -exec ... \;, if your find allows it. – glenn jackman Feb 28 '14 at 22:36
2

Assuming that PATTERN is actually ( ) and that something might go in between the ( ) and that they are not necessarily at the end of the line:

sed -i '/(.*)/ s/$/ ;/' test.txt
| improve this answer | |
1

Using ex (which is equivalent to vi -e/vim -e).

One file:

ex +"g/local/s/$/;/g" -cwq foo.txt

All test.txt files recursively:

ex +"bufdo g/local/s/$/;/g" -cxa **/test.txt

Note: Make sure that globbing option (**) is enabled by: shopt -s globstar if your shell supports it.

Note: The :bufdo command is not POSIX.

| improve this answer | |
0

Try:

sed --in-place '/PATTERN/s/.*/&;/' /path/to/file.txt
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.