【问题标题】:SED expansion not working even with double quotes in bash script即使在 bash 脚本中使用双引号,SED 扩展也不起作用
【发布时间】:2021-05-04 20:35:06
【问题描述】:

在使用 bash shell 脚本时遇到了一些问题。 基本上,我将值插入文件,然后从中创建一个变量,并尝试通过 sed 在另一个文件中附加和扩展变量值。

即:

cat animal.txt
Dog: 5
Ferret: 1
Cat: 10
Hamster: 2
NUM=$(cat animal.txt)

然后我想将变量“NUM”中的值附加到另一个文件 temp.txt:

cat temp.txt
country: England  city: Manchester
country: England  city: Hull
country: England  city: Liverpool
country: England  city: London

尝试了所有这些变化,但都不够:

sed 's/$/'"${NUM}"'/' temp.txt
sed 's/$/"${NUM}"/' temp.txt
sed 's/$/'"${NUM}"'/' temp.txt
sed "s/$/"${NUM}"/" temp.txt
sed "s/$/\${NUM}\/" temp.txt

这两个有点工作,但变量仍然从未扩展:

sed 's/$/"${NUM}"/' temp.txt
sed 's/$/"\${NUM}\"/' temp.txt
country: England  city: Manchester  "${NUM}"
country: England  city: Hull  "${NUM}"
country: England  city: Liverpool  "${NUM}"
country: England  city: London  "${NUM}"

即使我将整个表达式用双引号括起来:

sed "s/$/${NUM}/" temp.txt
sed "s/$/\${NUM}\/" temp.txt

我明白了:

sed: -e expression #1, char 27: unterminated `s' command
sed: -e expression #1, char 12: unterminated `s' command

期望的输出:

country: England  city: Manchester  Dog: 5
country: England  city: Hull        Ferret: 1
country: England  city: Liverpool   Cat: 10
country: England  city: London      Hamster: 2

country: England  city: Manchester  Dog:     5
country: England  city: Hull        Ferret:  1
country: England  city: Liverpool   Cat:     10
country: England  city: London      Hamster: 2

我知道我应该避免使用单引号并使用双引号,但我错过了什么? sed 在这里使用错误的工具吗?你认为 awk 会更好吗?

谢谢。

【问题讨论】:

  • 你想要的输出???
  • 用所需的输出更新了原始帖子^谢谢。
  • $NUM 包含整个文件,包括换行符;你想要paste,而不是sed

标签: bash shell sed expansion


【解决方案1】:

在这里使用 sed 是不是错误的工具? 可能是的。

不管怎样,如果你的animals.txt 文件足够小,你可以不用这个声明。

$ NUM="$(cat animal.txt)"; IFS=$'\n'; n=1; for num in $NUM; do i=0; while read -r line; do i=$((i + 1)); if [ $i -eq $n ]; then echo "$line" "$num"; n=$((n + 1)); break; fi; done < temp.txt; done

country: England  city: Manchester Dog: 5
country: England  city: Hull Ferret: 1
country: England  city: Liverpool Cat: 10
country: England  city: London Hamster: 2

但是对于大文件大小,awk 可能是更好的选择。

$ awk 'NR==FNR {num[FNR]=$0;next}{print $0 " " num[FNR]}' animal.txt temp.txt

country: England  city: Manchester Dog: 5
country: England  city: Hull Ferret: 1
country: England  city: Liverpool Cat: 10
country: England  city: London Hamster: 2

【讨论】:

  • 谢谢@Darkman!这两个选项也非常有效,非常有用。使用设置标签 \t 将它们分开时遇到了一些麻烦,但一切都很好。干杯。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-02
  • 2011-09-04
  • 2016-02-14
  • 2010-12-31
  • 1970-01-01
相关资源
最近更新 更多