Bash - 如何从一个文件中找到一行作为另一个文件中一行的一部分?

时间:2018-05-14 10:12:17

标签: bash shell awk grep find

我有两个文件:

的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文件:

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

1 个答案:

答案 0 :(得分:0)

编辑: 由于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