我有一个从网上下载的多行字符串:
toast the lemonade
blend with the lemonade
add one tablespoon of the lemonade
grill the spring onions
add the lemonade
add the raisins to the saucepan
rinse the horseradish sauce
Run Code Online (Sandbox Code Playgroud)
我已将其分配给$INPUT,如下所示:
toast the lemonade
blend with the lemonade
add one tablespoon of the lemonade
grill the spring onions
add the lemonade
add the raisins to the saucepan
rinse the horseradish sauce
Run Code Online (Sandbox Code Playgroud)
此时,$INPUT已准备好替换到我的目标文件中,如下所示:
INPUT=$(lynx --dump 'http://example.net/recipes' \
| python -m json.tool \
| awk '/steps/,/]/' \
| egrep -v "steps|]" \
| sed 's/[",]\|^ *//g; $d')
Run Code Online (Sandbox Code Playgroud)
当然,sed 抱怨未终止s命令未终止 - 这就是问题所在。
我当前使用的解决方法是在将echo $INPUT其交给 sed 之前,但随后不会保留换行符。echo删除换行符 - 这就是问题所在。
正确的输出应该保留其换行符。如何指示 sed 保留换行符?
黑客直接的答案是将所有换行符替换为\n,您可以通过添加来完成
| sed ':a $!{N; ba}; s/\n/\\n/g'
Run Code Online (Sandbox Code Playgroud)
到上面的长命令。一个更好的答案是使用 awk 来代替,因为将 shell 变量替换为代码总是一个坏主意,并且使用 sed 你别无选择:
awk -i inplace -v input="$INPUT" 'NR == 1, /OLDINPUT/ { sub(/OLDINPUT/, input) } 1' /home/test_file
Run Code Online (Sandbox Code Playgroud)
这需要 GNU awk 4.1.0 或更高版本-i inplace。