Awk replace string in line

大兔子大兔子 提交于 2020-01-06 17:57:09

问题


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


回答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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!