【问题标题】:Error while using while read; do grep读取时使用时出错;做 grep
【发布时间】:2013-10-30 08:22:49
【问题描述】:

我正在使用这个命令

cat text.csv | while read a ; do grep $a text1.csv >> text2.csv; done

text.csv 的文件名带有完整路径。文件名有空格。

示例:C:\Users\Downloads\File Name.txt

text1.csv 包含显示用户 ID 和带有完整路径的文件名的日志。

示例:MyName,C:\Users\Downloads\File Name.txt

当我运行命令时,我得到错误

grep: Name: No such file or Directory

我知道错误是因为文件名中的空格。我想知道如何消除此错误。

【问题讨论】:

  • 除非顺序很重要,否则最好使用grep -F -f text.csv text1.csv(如果您真的想要正则表达式元字符,而不是逐字匹配,请省略-F)。

标签: bash while-loop grep cat


【解决方案1】:

引用变量:

cat text.csv | while read a ; do grep "$a" text1.csv >> text2.csv; done

一般来说,您通常应该引用变量,除非您特别希望该值进行分词和通配符扩展。

【讨论】:

    【解决方案2】:

    使用带双引号的 grep 模式,否则 shell 会将其视为 grep 的不同参数:

    while read a ; do grep "$a" text1.csv >> text2.csv; done < text.csv
    

    不需要额外的cat,因此我在答案中更改了它。

    【讨论】:

      猜你喜欢
      • 2018-06-10
      • 2021-11-08
      • 2016-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-24
      相关资源
      最近更新 更多