bash 从文件名中提取数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7301026/
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 numbers from filename
提问by zetah
In BASH I thought to use sed
, but can't figure how to extract pattern instead usual replace.
在 BASH 中,我想使用sed
,但无法弄清楚如何提取模式而不是通常的替换。
For example:
例如:
FILENAME = 'blah_blah_#######_blah.ext'
文件名 = 'blah_blah_########_blah.ext'
number of ciphers (in above example written with "#" substitute) could be either 7 or 10
密码的数量(在上面的例子中用“#”代替)可以是 7 或 10
I want to extract only the number
我只想提取数字
回答by Victor Sanchez
You can use this simple code:
您可以使用这个简单的代码:
filename=zc_adsf_qwer132467_xcvasdfrqw
echo ${filename//[^0-9]/} # ==> 132467
回答by mvds
If all you need is to remove anything but digits, you could use
如果您只需要删除数字以外的任何内容,则可以使用
ls | sed -e s/[^0-9]//g
to get all digits grouped per filename (123test456.ext will become 123456), or
获取按文件名分组的所有数字(123test456.ext 将变为 123456),或
ls | egrep -o [0-9]+
for all groups of numbers (123test456.ext will turn up 123 and 456)
对于所有数字组(123test456.ext 将变为 123 和 456)
回答by glenn Hymanman
Just bash:
只是猛击:
shopt -s extglob
filename=zc_adsf_qwer132467_xcvasdfrqw
tmp=${filename##+([^0-9])}
nums=${tmp%%+([^0-9])}
echo $nums # ==> 132467
or, with bash 4
或者,使用 bash 4
[[ "$filename" =~ [0-9]+ ]] && nums=${BASH_REMATCH[0]}
回答by David W.
Is there any number anywhere else in the file name? If not:
文件名中是否还有其他数字?如果不:
ls | sed 's/[^0-9][^0-9]*\([0-9][0-9]*\).*//g'
Should work.
应该管用。
A Perl one liner might work a bit better because Perl simply has a more advanced regular expression parsing and will give you the ability to specify the range of digits must be between 7 and 10:
Perl one liner 可能会更好一些,因为 Perl 只是具有更高级的正则表达式解析,并且可以让您指定数字范围必须在 7 到 10 之间:
ls | perl -ne 's/.*\D+(\d{7,10}).*//;print if /^\d+$/;'
回答by Tomasz Nurkiewicz
$ ls -1
blah_blah_123_blah.ext
blah_blah_234_blah.ext
blah_blah_456_blah.ext
Having such files in a directory you run:
在您运行的目录中有这样的文件:
$ ls -1 | sed 's/blah_blah_//' | sed 's/_blah.ext//'
123
234
456
or with a single sed
run:
或单次sed
运行:
$ ls -1 | sed 's/^blah_blah_\([0-9]*\)_blah.ext$//'
回答by nitinr708
This will work for you -
这对你有用-
echo $FILENAME | sed -e 's/[^(0-9|)]//g' | sed -e 's/|/,/g'