问题
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:
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 usingcutor other command as in my example)replace a specific string somewhere else in the line by this variable (so not a field position like
$2, but really something likes/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! :)
回答1:
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
来源:https://stackoverflow.com/questions/39275121/awk-replace-string-in-line