unixawksedgrep

how to use sed on a grep matched string and display the complete output


here is what I'm trying to do..

I'm trying to cat a text file and display the full file and only changing some characters (which are appearing in other lines also), and use grep to match the key words from the selected line.

I am trying to do this all in one line command or commands, not by running a script.

For example, I have this text file, test_hasham.txt

cat test_hasham.txt

this is line one XXXXXX
this is line two XXXXXX
this is line three XXXXXX

I want to change "X" to "-" only on line which has word "two", the output should be all the lines in the original text file but only line with key word "two" changed.

this is line one XXXXXX
this is line two -----
this is line three XXXXXX

I'm trying something like this but it is changing all the "X" to "-"...how can I use grep and sed in one command to get the desires results.

this is what im doing but its changing all the X's to dashes, not only the line with the word two

cat test_hasham.txt |  (sed "s|X|-|g" ; grep two)
this is line one ------
this is line two ------
this is line three ------

In summary:

what i am getting:

cat test_hasham.txt |  (sed "s|X|-|g" ; grep two)
this is line one ------
this is line two ------
this is line three ------

what i want:

cat test_hasham.txt |  ( ****some magic sed + grep combo ****)
this is line one XXXXX
this is line two ------
this is line three XXXXX

Solution

  • You never need sed+grep for anything. In fact piping sed/grep/awk to sed/grep/awk is an antipattern, see https://porkmail.org/era/unix/award#grep.

    You should usually be using awk instead, e.g. using any awk:

    $ awk '/two/{ gsub(/X/,"-") } 1' test_hasham.txt
    this is line one XXXXXX
    this is line two ------
    this is line three XXXXXX
    

    but in this case you can do it with just sed, e.g. using any POSIX sed (improved from my original version courtesy of feedback from @potong):

    $ sed '/two/s/X/-/g' test_hasham.txt
    this is line one XXXXXX
    this is line two ------
    this is line three XXXXXX