[英]Modify bash variable with sed
Why doesn't the follow bash script work?为什么以下 bash 脚本不起作用? I would like it to output two lines like this:我想要 output 两行这样的:
XXXXXXX
YYYYYYY
It works if I change the sed line to use a filename instead of the variable, but I want to use the variable.如果我将 sed 行更改为使用文件名而不是变量,它会起作用,但我想使用变量。
#!/bin/bash
input=$(echo -e '=======\n-------\n')
for sym in = -; do
if [ "$sym" == '-' ]; then
replace=Y
else
replace=X
fi
printf "%s\n" "s/./$replace/g"
done | sed -f- <<<"$input"
The main problem is that you're giving sed two sources to read standard input from: the for loop that is fed through the pipe, and the variable coming through the here-string.主要问题是您给 sed 提供了两个源来读取标准输入:通过 pipe 提供的 for 循环,以及通过 here-string 提供的变量。 As it turns out, the here-string gets precedence and sed complains that there are extra characters after a command ( =
is a command).事实证明,这里的字符串优先,sed 抱怨命令后面有多余的字符( =
是命令)。
Instead of a here-string, you could use process substitution:您可以使用进程替换来代替此处的字符串:
for sym in = -; do
if [ "$sym" == '-' ]; then
replace=Y
else
replace=X
fi
printf "%s\n" "s/./$replace/g"
done | sed -f- <(printf '%s\n' '=======' '-------')
You'll notice that the output isn't what you want, though, namely但是,您会注意到 output 不是您想要的,即
YYYYYYY
YYYYYYY
This is because the sed script you end up with looks like this:这是因为您最终得到的 sed 脚本如下所示:
s/./X/g
s/./Y/g
No matter what you do first, the last command replaces everything with Y
.无论您先做什么,最后一个命令都会用Y
替换所有内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.