string 使用bash从字符串中提取整数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6388046/
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
Extract integer from string using bash
提问by Open the way
I tried to find the solution here but could not; given strings like
我试图在这里找到解决方案,但找不到;给定的字符串,如
ABC3
DFGSS34
CVBB3
how do I extract the integers so I get
我如何提取整数所以我得到
3
34
3
??
??
回答by anubhava
Just a simple sed command will do the job:
只需一个简单的 sed 命令即可完成这项工作:
sed 's/[^0-9]//g' file.txt
OUTPUT
输出
3
34
3
回答by paxdiablo
For a bash-only solution, you can use parameter patter substition:
对于仅 bash 的解决方案,您可以使用参数模式替换:
pax$ xyz=ABC3 ; echo ${xyz//[A-Z]/}
3
pax$ xyz=DFGSS34 ; echo ${xyz//[A-Z]/}
34
pax$ xyz=CVBB3 ; echo ${xyz//[A-Z]/}
3
It's very similar to sed
solutions but has the advantage of not having to fork another process. That's probably not important for small jobs but I've had situations where this sort of thing was done to many, many lines of a file and the non-forking is a significant speed boost.
它与sed
解决方案非常相似,但具有不必分叉另一个进程的优点。这对于小型工作来说可能并不重要,但我遇到过这样的情况,对文件的许多行都做了这种事情,并且非分叉是显着的速度提升。
回答by sorpigal
How about using tr
?
怎么用tr
?
for s in ABC3 DFGSS34 CVBB3 ; do
tr -cd 0-9 <<<"$s"
echo
done
回答by bmk
What about a grep
version?
一个grep
版本呢?
grep -o '[0-9]*' file.txt