Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Awk replace string in line

Tags:

bash

sed

awk

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! :)

like image 755
tlorin Avatar asked Apr 20 '26 18:04

tlorin


2 Answers

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
like image 77
Claes Wikner Avatar answered Apr 23 '26 08:04

Claes Wikner


What you want to do is super-easy using sed

$ sed -E <file '
s/(how.*)hello/\1how/
s/(you.*)hello/\1you/
s/(are.*)hello/\1are/'
/foo/bar/how /SOME_TEXT_HERE/how
/foo/bar/are are/SOME_OTHER_TEXT
/foo/bar/you you
$
like image 22
gboffi Avatar answered Apr 23 '26 09:04

gboffi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!