我正在尝试替换。我的替换字符串存储在名为$var
的变量中。
输入是:
This is a sample string
which is of multiline
变量是:
var="this is var content this is var content this is var content this is var
this is var content this is var content this is var content this is
var content this is var content this is var content"
变量替换工作:
echo "This is a sample string
which is of multiline" |sed -r "/sample/ {n;s/^/ $var/g}"
This is a sample string
this is var content this is var content this is var content this is var content this is var content this is var content this is var content this is var content this is var content this is var content this is var content this is var contentwhich is of multiline
但是当我使用fmt
时,变量替换不起作用:
var=$(echo $var|fmt)
echo "This is a sample string
which is of multiline" |sed -r "/sample/ {n;s/^/ $var /g}"
sed: -e expression #1, char 84: unterminated `s' command
我认为这是因为fmt
引起的EOL,所以有没有解决方法?
使用fmt
的原因:我需要将输出限制为每行80个字符。
答案 0 :(得分:2)
运行以下here:
#!/bin/bash
# GNU bash, version 4.3.46
var="this is var content this is var content this is var content this is var
this is var content this is var content this is var content this is
var content this is var content this is var content"
echo "This is a sample string
which is of multiline" |sed -r "/sample/ {n;s/^/ $var/g}"
将导致:
sed: -e expression #1, char 88: unterminated `s' command
这是因为$var
扩展为多行字符串,因此sed参数如下所示:
... sed -r '/sample/ {n;s/^/ this is var content this is var content this is var content this is var
this is var content this is var content this is var content this is
var content this is var content this is var content/g}'
Commands within a script or script-file can be separated by semicolons (;) or newlines (ASCII 10).
sed将每一行解释为一个单独的命令,因此它会找到未终止的'' s'命令。
懒惰的解决方法是用' \ n'替换换行符。在$ var:
var="this is var content this is var content this is var content this is var
this is var content this is var content this is var content this is
var content this is var content this is var contenat"
var=${var//$'\n'/\\n} # puff!
echo "This is a sample string
which is of multiline" |sed -r "/sample/ {n;s/^/ $var/g}"
" good"方式是google smth like"用bash"中的多行字符串替换模式并使用awk:
var="this is var content this is var content this is var content this is var
this is var content this is var content this is var content this is
var content this is var content this is var contenat"
echo "This is a sample string
which is of multiline" | awk -v "r=$var" '/sample/{print;printf r;next;}1'