Grep来自存储在csv文件中的变量

时间:2017-09-15 08:45:56

标签: bash

我试着在" test.csv"来自book.1的内容。

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&amp; test.csv中有book1.csv的内容

我做错了什么?

修改

SAMPLE输入book1.csv

HOSTNAME
TEST1
TEST2

示例输入test.csv

blank,TEST1.abc.123,blank,date

我想从test.csv

中的book1.csv获取每一行
Cat -a book1 result

TEST1^M$

2 个答案:

答案 0 :(得分:2)

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

您可以将此命令与tr一起使用,在\r运行.csv之前从grep文件中删除grep -Ff <(tr -d '\r' < book1.csv) <(tr -d '\r' < test.csv) blank,TEST1.abc.123,blank,date

tr -d '\r' < book1.csv

\r将从给定文件中删除{{1}}或回车符。

答案 1 :(得分:1)

使用fgrep应该有效。根据您提供的数据,它提供:

fgrep -f book1.csv test.csv

输出:

blank,TEST1.abc.123,blank,date

fgrep严格等同于grep -F

来自grep man page:

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)
相关问题