BASH:如何提取子由特定的文本包围 [英] BASH: How to extract substring that is surrounded by specific text
本文介绍了BASH:如何提取子由特定的文本包围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图提取遵循特定模式的文件名编号:
I am trying to extract numbers from file names that follow a specific pattern:
file-8923489_something.txt
another_file-8923489_something.txt
some-other_file-8923489_something.txt
欲提取是文本文件级和_something,将与上述3的文件名的工作之间的数目。
I want to extract the number that is between text "file-" and "_something" that will work with the above 3 file names.
什么是去最好的方法?
是否有可能做到这一点只能通过运营商,如##和%%?如何是这样的:
Is it possible to do this using operators only, such as ## and %%? How about something like:
filename=file-8923489_something.txt
file=${${filename##*file}%%_something}}
但是,如我所料没有工作。
However, it didn't work as I expected.
推荐答案
使用pre BASH正则表达式:
Using pre BASH regex:
x="some-other_file-8923489_something.txt"
[[ "$x" =~ file-([0-9]*)_something ]] && echo ${BASH_REMATCH[1]}
8923489
或本的grep -P
也将工作:
grep -oP "file-\K\d+(?=_something)" file
8923489
8923489
8923489
或使用awk的:
awk -F 'file-|_something' '{print $2}' file
8923489
8923489
8923489
这篇关于BASH:如何提取子由特定的文本包围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文