gpt4 book ai didi

string - grep 两个文件 (a.txt, b.txt) - b.txt 中有多少行以 a.txt 中的单词开始(或结束) - 输出 : 2 files with the results

转载 作者:行者123 更新时间:2023-11-29 09:48:00 28 4
gpt4 key购买 nike

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

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

我想知道 b.txt 中有多少个字符串以 a.txt 中的单词结尾

例子:一个.txt

apple
peach
potato

b.txt

greenapple
bigapple
rottenapple
pinkpeach
xxlpotatoxxx

输出

3 apple greenapple bigapple rottenapple
1 peach pinkpeach

我想用 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{ # 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

关于string - grep 两个文件 (a.txt, b.txt) - b.txt 中有多少行以 a.txt 中的单词开始(或结束) - 输出 : 2 files with the results,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22421188/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com