使用fmt后执行变量替换

时间:2018-05-23 10:40:34

标签: bash awk sed

我正在尝试替换。我的替换字符串存储在名为$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个字符。

1 个答案:

答案 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}'

根据this sed manual

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'