【问题标题】:Grep from variable stored in a csv file来自存储在 csv 文件中的变量的 Grep
【发布时间】:2018-02-24 09:35:38
【问题描述】:

我正在尝试从 book.1 的内容中查找“test.csv”中的所有内容

while IFS= read -r result
do
grep -r $result test.csv >> output.csv

echo $result

done<book1.csv

我的书 1 有 1 行数据是 A 列。

我正在屏幕上显示 book1.csv 的结果,因此它可以正确解析,但在 output.csv 中我什么也没得到

我已经手动检查了 grep 并且 test.csv 中有 book1.csv 的内容

我做错了什么?

编辑

SAMPLE 输入 book1.csv

HOSTNAME
TEST1
TEST2

样本输入 test.csv

blank,TEST1.abc.123,blank,date

我想从 book1.csv 中获取 test.csv 中的每一行

Cat -a book1 result

TEST1^M$

【问题讨论】:

  • 当我在没有脚本的情况下执行“grep -r TEST1 test.csv >> output.csv”时,我得到了预期的数据,所以它与我的 $result 变量有关
  • grep -Ff book1.csv test.csv 通常可以工作,但您还必须提供来自test.csv 的示例数据。还要检查cat -A book1.csvcat -A test.csv 的输出,确保没有DOS 回车。
  • 添加了示例输入,当我执行上述 grep -Ff 时,我什么也得不到。但是,如果我执行 grep TEST1 test.csv 我会得到结果,所以我不确定出了什么问题
  • 为 book1.csv 添加了 cat -a

标签: bash


【解决方案1】:

最初怀疑您的 .csv 文件的 DOS 行以 \r 字符结尾,这导致 grep -f 不匹配,因为 Unix 文件仅以 \n 结尾。

您可以将此命令与tr 一起使用,在运行grep 之前从两个.csv 文件中删除\r

grep -Ff <(tr -d '\r' < book1.csv) <(tr -d '\r' < test.csv)

blank,TEST1.abc.123,blank,date

tr -d '\r' &lt; book1.csv 将从给定文件中删除\r 或回车符。

【讨论】:

    【解决方案2】:

    使用fgrep 应该可以。根据您提供的数据,它给出:

    fgrep -f book1.csv test.csv
    

    输出:

    blank,TEST1.abc.123,blank,date
    

    fgrep 严格等价于grep -F

    来自 grep 手册页:

    Matcher Selection
       -F, --fixed-strings
              Interpret PATTERN as a list of fixed strings, separated by newlines, any of which is to be matched.  (-F is specified by POSIX.)
    
    
    Matching Control
       -f FILE, --file=FILE
              Obtain  patterns  from FILE, one per line.  The empty file contains zero patterns, and therefore matches nothing.  (-f is specified
              by POSIX.)
    

    正如 anubhava 所指出的,您需要删除 DOS 字符。为此,只需使用dos2unix 命令:

    fgrep -f <(dos2unix book1.csv) <(dos2unix test.csv)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-01
      • 2018-01-10
      • 2015-10-13
      • 2013-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多