bash awk 替换 shell 变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20629581/
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 substitute shell variables
提问by Dan-Simon Myrland
I am struggling with awk substitution, for some reason the following code does not substitute anything, it just prints the output unaltered. Can anyone see what I am missing here? Any help would be very much appreachiated! (PS! The $DOCPATH and $SITEPATH are shell variables, they work perfectly fine in my awk setup).
我正在为 awk 替换而苦苦挣扎,出于某种原因,以下代码没有替换任何内容,它只是打印未更改的输出。谁能看到我在这里缺少什么?任何帮助都会非常有用!(PS!$DOCPATH 和 $SITEPATH 是 shell 变量,它们在我的 awk 设置中工作得很好)。
awk -v docpath="$DOCPATH" -v sitepath="$SITEPATH" '{ sub( /docpath/, sitepath ) } { print }'
回答by devnull
Saying:
说:
sub( /docpath/, sitepath )
causes awk
to replace the pattern docpath
, not the variable docpath
.
导致awk
替换模式docpath
,而不是变量docpath
。
You need to say:
你需要说:
awk -v docpath="$DOCPATH" -v sitepath="$SITEPATH" '{sub(docpath, sitepath)}1' filename
回答by perreal
Couldn't help to write this in sed:
忍不住在 sed 中写下这个:
sed 's/'"$DOCPATH"'/'"$SITEPATH"'/' input
回答by Kevin
/docpath/
will search for the literal string "docpath", not the variable as you want. Just use sub(docpath, sitepath)
.
/docpath/
将搜索文字字符串“docpath”,而不是您想要的变量。只需使用sub(docpath, sitepath)
.
N.b. if there could be multiple matches in the same line, you'll want gsub
instead of sub
.
注意,如果同一行中可能有多个匹配项,您将需要gsub
而不是sub
.