Awk replace string in line

19,060
awk '{sub(/are hello/,"are are")sub(/you hello/,"you you")}1' file

/foo/bar/how /SOME_TEXT_HERE/hello
/foo/bar/are are/SOME_OTHER_TEXT
/foo/bar/you you
Share:
19,060
tlorin
Author by

tlorin

I'm a new comer at bio-informatics and as I found answers of basic questions on this forum I found it cool and thought that I should join this community! For the moment, I'm mostly asking questions, but I hope in the future I'll get to answer some! :)

Updated on June 04, 2022

Comments

  • tlorin
    tlorin almost 2 years

    NOTE: This question looks like a previously posted one, but as mentioned in the comments, it turned out to be a chameleon question. I accepted the answer, and I'm posting here the same problem but with slightly different "solution conditions".


    I have a file test.txt like this (but containing many more lines)

    /foo/bar/how /SOME_TEXT_HERE/hello
    /foo/bar/are hello/SOME_OTHER_TEXT
    /foo/bar/you hello
    

    I want to get this output:

    /foo/bar/how /SOME_TEXT_HERE/how
    /foo/bar/are are/SOME_OTHER_TEXT
    /foo/bar/you you
    

    I have tried this:

    while read line
    do
    bla=$(echo $line | cut -f4 -d"/" | cut -f1 -d" ")
    sed -i "s/hello/$bla/" test.txt
    done <test.txt
    

    But the output is:

    /foo/bar/how /SOME_TEXT_HERE/how
    /foo/bar/are how/SOME_OTHER_TEXT
    /foo/bar/you how
    

    NOTE:

    I would like the solution to:

    1. allow me to define a variable (here, bla) that I will define manually and differently from one file to the other (so not using sthg like basic field position), but using cut or other command as in my example)

    2. replace a specific string somewhere else in the line by this variable (so not a field position like $2, but really something like s/hello/$bla)

    I'm not sure of this is possible though (obviously I don't know how to do this by myself...), but thanks for your time trying! :)