Bash:如何从字符串中取出一个数字?(可能是正则表达式)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10486575/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 02:13:11  来源:igfitidea点击:

Bash: how to take a number from string? (regular expression maybe)

regexbashgrep

提问by micobg

I want to get a count of symbols in a file.

我想获取文件中的符号数。

wc -c f1.txt | grep [0-9]

But this code return a line where grep found numbers. I want to retrun only 38. How?

但此代码返回一行 grep 找到数字。我只想重新运行38。如何?

回答by anubhava

You can use awk:

您可以使用 awk:

wc -c f1.txt | awk '{print }'

OR using grep -o:

或使用grep -o

wc -c f1.txt | grep -o "[0-9]\+"

OR using bash regex capabilities:

或使用 bash 正则表达式功能:

re="^ *([0-9]+)" && [[ "$(wc -c f1.txt)" =~ $re ]] && echo "${BASH_REMATCH[1]}"

回答by glenn Hymanman

pass data to wcfrom stdin instead of a file: nchars=$(wc -c < f1.txt)

将数据wc从 stdin 而不是文件传递到:nchars=$(wc -c < f1.txt)