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

时间:2016-05-28 17:33:03

标签: bash shell awk sed ksh

长话短说,我试图通过使用变量来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 command not found”错误。我尝试将文本与变量结合起来使其工作:

VAR1= "'^"$ii"'"

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

'^123
'

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

2 个答案:

答案 0 :(得分:1)

命令grep '^ii' list.txt中混合了一些东西。字符^用于行的开头,$用于变量的值。 如果要在行开头的变量ii中grep 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 !

答案 1 :(得分:0)

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