通过组合文本 + 另一个变量来创建变量

Create variable by combining text + another variable

长话短说,我正在尝试使用变量 grep 文本文件第一列中包含的值。

这是脚本示例,其中 grep 命令不起作用:

for ii in `cat list.txt`
do
    grep '^$ii' >outfile.txt
done

list.txt 的内容:

123,"first product",description,20.456789
456,"second product",description,30.123456
789,"third product",description,40.123456

如果我执行 grep '^123' list.txt,它会产生正确的输出...只是 list.txt 的第一行。

如果我尝试使用变量(即 grep '^ii' list.txt),我会收到“找不到 ^ii 命令”错误。我尝试将文本与变量结合起来使其工作:

VAR1= "'^"$ii"'"

但是 VAR1 变量在 $ii 变量之后包含一个回车符 return:

'^123
'

我尝试了一大堆东西来删除 cr/lr(即 sed 和 awk),但无济于事。必须有一种更简单的方法来使用变量执行 grep 命令。我宁愿继续使用 grep 命令,因为它在手动执行时效果很好。

#!/bin/sh
# Read every character before the first comma into the variable ii.
while IFS=, read ii rest; do
    # Echo the value of ii. If these values are what you want, you're done; no
    # need for grep.
    echo "ii = $ii"
    # If you want to find something associated with these values in another
    # file, however, you can grep the file for the values. Use double quotes so
    # that the value of $ii is substituted in the argument to grep.
    grep "^$ii" some_other_file.txt >outfile.txt
done <list.txt

您在命令 grep '^ii' list.txt 中混入了东西。字符 ^ 表示行的开头,$ 表示变量的值。 当你想在行首的变量 ii 中 grep for 123 时,使用

ii="123"
grep "^$ii" list.txt

(此处应使用双引号)
学习好习惯的好时机:继续使用小写的变量名(做得好)并使用大括号(不要伤害,在其他情况下需要):

ii="123"
grep "^${ii}" list.txt

现在我们都忘记了一些事情:我们的 grep 也将匹配 1234,"4-digit product",description,11.1111。在 grep:

中包含一个 ,
ii="123"
grep "^${ii}," list.txt

您是如何得到“^ii 命令未找到”错误的?我认为你使用了反引号(嵌套命令的旧方法,更好的是 echo "example: $(date)")并且你写了

grep `^ii` list.txt # wrong !