grep两个文件(a.txt,b.txt) - b.txt中有多少行使用a.txt中的单词开始(或结束) - 输出:2个文件结果 [英] grep two files (a.txt, b.txt) - how many lines in b.txt starts (or ends) with the words from a.txt - output: 2 files with the results

查看:426
本文介绍了grep两个文件(a.txt,b.txt) - b.txt中有多少行使用a.txt中的单词开始(或结束) - 输出:2个文件结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我问太多,但也许你可以帮助这个问题。



a.txt包含字词,b.txt包含字符串。



我想知道来自b.txt的字符串结尾有来自a.txt的字符



示例:
a.txt

  apple 
peach
potato

b.txt

  greenapple 
bigapple
rottenapple
pinkpeach
xxlpotatoxxx

输出

  3 apple greenapple bigapple rottenapple 
1 peach pinkpeach
pre>

我想使用grep的解决方案,因为它的方式比awk更快。



你能请帮助我吗?

解决方案

这是一个 awk 解决方案

  awk'FNR == NR {a [$ 1] ++; next} {for(i in a){if($ 0〜i$) {b [i] ++; w [i] = w [i]?w [i] FS $ 0:$ 0}}} END {for(j in b)print b [j],j,w [j] 'a.txt b.txt 
3 apple greenapple bigapple rottenapple
1 peach pinkpeach

使用 grep



不会很简单或不可能它工作(它不是那么复杂)?

  awk'
FNR == NR {#文件(a.txt)
a [$ 1] ++#将其存储在数组中a
next}#跳转到下一个记录
{#为文件b.txt运行此零件
for(i in a){#循环遍历数组中的所有数据a
if($ 0〜i$){#b.txt在它的末尾有一些数组吗?
b [i] ++#是,计数
w [i] = w [i]?w [i] FS $ 0:$ 0#并存储它在数组中找到的记录w
}
}
}
END {#当两个文件都被读取时,END部分
用于(j in b)#循环遍历数组b中的所有元素,
print b [j],j,w [j]}#打印数组b,索引和数组w
'a.txt b.txt#读取两个文件


I know I ask too much, but maybe you can help with this problem too.

a.txt contains words, b.txt contains strings.

I would like to know how many string from b.txt ends with the words from a.txt

Example: a.txt

apple
peach
potato

b.txt

greenapple
bigapple
rottenapple
pinkpeach
xxlpotatoxxx

Output

3 apple greenapple bigapple rottenapple
1 peach pinkpeach

I would like to have a solution with grep, since it is way more faster than awk.

Can you guys please help me?

解决方案

Here is an awk solution

awk 'FNR==NR{a[$1]++;next} {for (i in a) {if ($0~i"$") {b[i]++;w[i]=w[i]?w[i] FS $0:$0}}} END {for (j in b) print b[j],j,w[j]}' a.txt b.txt
3 apple greenapple bigapple rottenapple
1 peach pinkpeach

It will not be simple or not possible at all to do this with grep

How does it work (it's not so complicated)?

awk '
FNR==NR{                        # Run this part for first file (a.txt) only
  a[$1]++                       # Store it in an array a
  next}                         # Skip to next record
  {                             # Run this part for file b.txt
  for (i in a) {                # Loop trough all data in array a
    if ($0~i"$") {              # Does b.txt have some from array a at the end of it?
      b[i]++                    # Yes , count it
      w[i]=w[i]?w[i] FS $0:$0   # and store the record it found it in in array w
      }
    }
  } 
END {                           # When both file has been read do the END part
  for (j in b)                  # Loop trough all element in array b and
    print b[j],j,w[j]}          # Print array b, index and array w
  ' a.txt b.txt                 # Read the two files

这篇关于grep两个文件(a.txt,b.txt) - b.txt中有多少行使用a.txt中的单词开始(或结束) - 输出:2个文件结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆