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



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

下面是脚本的示例,其中包含不起作用的 grep 命令:

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

列表内容.txt :

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

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

如果我尝试使用该变量(即grep '^ii' list.txt),则会出现"找不到^ii命令"错误。 我试图将文本与变量组合以使其工作:

VAR1= "'^"$ii"'"

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

'^123
'

我已经尝试了一系列东西来删除cr/lr(即sed和awk),但无济于事。必须有一种更简单的方法来使用该变量执行 grep 命令。 我宁愿继续使用 grep 命令,因为它在手动执行时可以完美运行。

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

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 !
#!/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

最新更新