我使用 Awk 搜索关键字
<replaceme>
并将其替换为字符串。该字符串包含字符“
",但 Awk 将其解释为新行。我真的想保留两个字符 \
和 n
。
我有一个包含真正的新行的字符串,我需要将其替换为字符“ ”。 它有效:
mytext=$'hello\nhow are you'
mytext2=${mytext//$'\n'/\\n}
echo "$mytext"
hello
how are you
echo "$mytext2"
hello\nhow are you
然后我在文本中有一个关键字
<replaceme>
,我想将其替换为$mytext2
的内容
echo 'this is the text: <replaceme>' |
awk -v srch="<replaceme>" -v repl="$mytext2" '{
gsub(srch,repl,$0); print $0 }'
我得到了这个结果。
this is the text: hello
how are you
但我想要:
this is the text: hello\nhow are you
请问如何进行?
注意:事实上,文本“this is the text:”位于一个文件中,我使用 cat myfile.txt | awk...
您可以使用这个
awk
解决方案:
mytext=$'hello\nhow are you'
echo 'this is the text: <replaceme>' |
awk -v srch="<replaceme>" -v repl="${mytext//$'\n'/\\\\n}" '{gsub(srch,repl)} 1'
this is the text: hello\nhow are you
BASH 替换
${mytext//$'\n'/\\\\n}
将在将该字符串作为 \n
参数 \\n
传递之前将 awk
的每个实例替换为 repl
。
纯awk解决方案(没有bash):
echo 'this is the text: <replaceme>' |
awk -v srch="<replaceme>" '
BEGIN {
repl = ARGV[1]
gsub(/\n/, "\\n", repl)
delete ARGV[1]
}
{
gsub(srch, repl)
} 1' "$mytext"
this is the text: hello\nhow are you