作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我知道我要求太多,但也许你也可以帮助解决这个问题。
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/
我是一名优秀的程序员,十分优秀!