bash awk 替换行中的字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39275121/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Awk replace string in line
提问by tlorin
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)
我有一个test.txt
这样的文件(但包含更多行)
/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 usingcut
or 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
)
允许我定义一个变量(在这里,
bla
),我将手动定义一个文件到另一个文件(所以不要像基本字段位置那样使用 sthg),而是cut
像我的例子一样使用或 其他命令)用这个变量替换行中其他地方的特定字符串(所以不是像 那样的字段位置
$2
,而是像 那样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! :)
我不确定这是否可行(显然我自己不知道如何做到这一点......),但感谢您的时间尝试!:)
回答by Claes Wikner
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