【问题标题】:Create variable by combining text + another variable通过组合文本 + 另一个变量来创建变量
【发布时间】:2016-05-28 17:33:03
【问题描述】:

长话短说,我正在尝试使用变量 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 命令,因为它在手动执行时可以完美运行。

【问题讨论】:

  • 另外,显示你想要的输出。
  • 感谢您的回复!在这种情况下,所需的输出只是文件的第一行。基本上,我希望 grep 搜索第一列并忽略其余列。如果使用不带标志的 grep,则会显示文件的每一行。

标签: bash shell awk sed ksh


【解决方案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 command not found”错误的?我认为您使用了反引号(嵌套命令的旧方法,更好的是echo "example: $(date)")并且您写道

grep `^ii` list.txt # wrong !

【讨论】:

  • 谢谢沃尔特,成功了!除了您的回复,我发现我需要对 list.txt 文件执行 dos2unix,因为它是在 Windows 中生成的。感谢所有回复的人!!!
【解决方案2】:
#!/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

【讨论】:

    猜你喜欢
    • 2014-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-31
    • 1970-01-01
    • 2020-04-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多