英文:
Shell script to sum number between "nmemb:(" and ")"
问题
cat X | grep -o 'nmemb[^_]*$' | doSumBetweenBracket()
英文:
I have a file called "X" which has a lot of nmemb:(123) , nmemb:(56789) , ....
cat X | grep -o 'nmemb[^_]*$'
output like :
nmemb:(16384)
nmemb:(16384)
nmemb:(16384)
nmemb:(5608)
nmemb:(10776)
nmemb:(16384)
nmemb:(16384)
nmemb:(16384)
nmemb:(16384)
nmemb:(16384)
How can I sum these number between "nmemb:(" & ")" ? like :
cat X | grep -o 'nmemb[^_]*$' | doSumBetweenBracket()
答案1
得分: 2
#### 像这样:
$ grep -oP 'nmemb:\(\K\d+' X | paste -sd '+' | bc
或
grep -oP 'nmemb:\(\K\d+' X | awk '{c+=$1}END{print c}'
或者仅使用`GNU` `awk`(没有管道)
awk '/memb:\([0-9]/{match($0, /[0-9]+/, a);c+=a[0]}END{print c}' X
#### 输出
147456
英文:
Like this:
$ grep -oP 'nmemb:\(\K\d+' X | paste -sd '+' | bc
or
grep -oP 'nmemb:\(\K\d+' X | awk '{c+=$1}END{print c}'
or with GNU
awk
only (no pipes)
awk '/memb:\([0-9]/{match($0, /[0-9]+/, a);c+=a[0]}END{print c}' X
Output
147456
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论