linuxbashsed

linux - sed command to search a substring in a file, then modify that a substring in that line only and keep the lines in the file


With linux the sed command is it possible to do a sed command to search a substring in a file, then modify that a substring in that line only and keep the lines in the file, in one command line?

example file test.txt

foo bar
goo bar

I tried the following but it only saves the line affected not the whole file.

sed -in '/foo/{s/bar/bah/;p}' test.txt

Is it possible to do this in one sed command?


Solution

  • This is a task for awk because it's cleaner, more hardened and easier to maintain:
    awk '$1=="foo"{sub("bar", "bah", $2)} 1' file 
    
    to edit in place, you can use sponge:
    awk ...... file | sponge file
    

    or use -i inplace (require GNU awk).

    To decompose a bit:

    This is the awk basics:

    condition{action}
    

    so

    Pseudo code awk code
    if $1=="foo" first column == foo
    then {sub("bar", "bah", $2)} substitution with sub() on the second column
    finally 1 implicit print on a true condition (1 is true)