【问题标题】:Bash - How to find line from one file as a part of a line from another file?Bash - 如何从一个文件中查找行作为另一个文件行的一部分?
【发布时间】:2018-05-14 10:12:16
【问题描述】:

我有两个文件:

1.txt

/stackoverflow.com/questions
/stackoverflow.com/reports
/stackoverflow.com/answers

2.txt

/stackoverflow.com/questions/18959800/grep-each-line-from-a-file-in-another-file
/stackoverflow.com/answers/18984800/grep-each-line-from
/stackoverflow.com/questions/20559800/line-from-a-file-in-another-file
/stackoverflow.com/ask/9959800/file-in-another-file-second_line

如果来自 1.txt 的行是来自 2.txt 的行的一部分,则打印此行。 如果 2.txt 中的一行不匹配,则打印此行。

我想得到这样的 output.txt 文件:

输出.txt:

/stackoverflow.com/questions/
/stackoverflow.com/reports/
/stackoverflow.com/answers/
/stackoverflow.com/ask/9959800/file-in-another-file-second_line

可以将所有行放在一个文件中:

/stackoverflow.com/questions
/stackoverflow.com/reports
/stackoverflow.com/answers
/stackoverflow.com/questions/18959800/grep-each-line-from-a-file-in-another-file
/stackoverflow.com/answers/18984800/grep-each-line-from
/stackoverflow.com/questions/20559800/line-from-a-file-in-another-file 
/stackoverflow.com/ask/9959800/file-in-another-file-second_line

【问题讨论】:

标签: bash shell awk grep find


【解决方案1】:

编辑: 由于 OP 添加了之前 Input_file 中的行,因此也需要编辑解决方案,如下所示。

awk 'FNR==NR{a[$0]=$0;next} {for(i in a){if(match($0,a[i])){print substr($0,RSTART,RLENGTH);b[i]=i;next}};print;} END{for(k in a){if(b[k]==""){print a[k]}}}' 1.txt 2.txt

现在也添加非单线形式的解决方案。

awk '
FNR==NR{
  a[$0]=$0;
  next}
{
  for(i in a){
    if(match($0,a[i])){
      print substr($0,RSTART,RLENGTH);
      b[i]=i;
      next}};
    print}
END{
  for(k in a){
    if(b[k]==""){
      print a[k]}}
}
' 1.txt 2.txt

您能否尝试关注一下,如果这对您有帮助,请告诉我。

awk 'FNR==NR{a[$0]=$0;next} {for(i in a){if(match($0,a[i])){print substr($0,RSTART,RLENGTH);next}};print}' 1.txt 2.txt

【讨论】:

  • 看起来不错,但是一个case不符合,我的不好我没有提到它如果1.txt中的任何一行在2.txt中不符合,也应该打印
  • @MaciejNowak,请检查我的 EDIT 解决方案,如果对您有帮助,请告诉我。
  • 是的,你帮了我,谢谢你。但是重复行有一个小问题,但是 sort -u 解决了它。
  • 你可以接受他的回答,他很努力帮助你。
猜你喜欢
  • 1970-01-01
  • 2021-04-27
  • 1970-01-01
  • 2019-07-26
  • 1970-01-01
  • 1970-01-01
  • 2014-02-06
  • 2013-01-06
  • 2023-03-18
相关资源
最近更新 更多