【问题标题】:compare a set of strings from one csv file in another csv file using Unix Shell script使用 Unix Shell 脚本比较另一个 csv 文件中一个 csv 文件中的一组字符串
【发布时间】:2017-06-11 06:07:36
【问题描述】:

我是 bash Shell 脚本的新手。我要求我有一个查找文件 (csv),其中有一组字符串,如下所示。

文件1:

text1
text2
text3

我必须检查file1中的字符串是否存在于file2中。

文件2:

s.no    desc
1       text5
2       text3
3       text2
4       text9

如果 file1 中的字符串存在于 file2 中,那么我必须在一个新文件 file3 中打印输出,其中包含 s.no 和找到的字符串。请帮忙。

【问题讨论】:

  • 请将该示例输入的示例输出添加到您的问题中。
  • 我的输出文件可能像 S.no desc 3 text2 2 text3
  • 您的列是如何分隔的?一个空格、多个空格还是一个制表符?
  • 这是一个标签分隔
  • 使用连接、排序和 bash:join -1 1 -2 2 -t $'\t' --header <(echo; sort file1) <(sort -t $'\t' -k2,2 file2) -o 2.1,2.2

标签: bash shell csv unix


【解决方案1】:

使用

grep --file=file1 file2

grep -f file1 file2

来自 grep 的手册页

  -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.)

注意:如果您只想完全匹配单词,请添加 -w。所以footext3bar不会和text3匹配。

file1 也包含正则表达式关键字,如@9​​87654329@ 或^ 然后添加-F

所以更新的命令会是

grep -Fwf file1 file2

例子

bash-4.2$ cat file1
text1
text2
text3
bash-4.2$ cat file2
s.no    desc
1       text5
2       text3
3       text2
4       text9
bash-4.2$
bash-4.2$ grep --file=file1 file2
2       text3
3       text2

【讨论】:

  • 感谢 Utsav。这是完美的工作。如果我的 file2 的值如下 s.no desc 1 like text5 is xxxx 2 some text3 is qwe 3 random text2 is dfgg 4 call text9 has phdg 我如何检查文件2中是否存在查找字符串?比方说,这是一种错误检查机制,我们使用 file1 中的特定错误关键字在日志文件 (file2) 中进行搜索。
  • 酷。请阅读What should I do when someone answers my question,以便可以关闭问题。
猜你喜欢
  • 1970-01-01
  • 2014-12-10
  • 1970-01-01
  • 2013-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-12
相关资源
最近更新 更多