BASH: How to extract substring that is surrounded by specific text

て烟熏妆下的殇ゞ 提交于 2019-12-20 06:12:43

问题


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

I want to extract the number that is between text "file-" and "_something" that will work with the above 3 file names.

What is the best way to go about this?

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.


回答1:


Using pre BASH regex:

x="some-other_file-8923489_something.txt"
[[ "$x" =~ file-([0-9]*)_something ]] && echo ${BASH_REMATCH[1]}
8923489

OR this grep -P will also work:

grep -oP "file-\K\d+(?=_something)" file
8923489
8923489
8923489

OR using awk:

awk -F 'file-|_something' '{print $2}' file
8923489
8923489
8923489



回答2:


With grep:

$ echo "file-8923489_something.txt
another_file-8923489_something.txt
some-other_file-8923489_something.txt" | grep -Po '(?<=file-)\d+'
8923489
8923489
8923489

Or with pure bash:

d="your_string"
d1=${d%_*}
your_final_string=${d1##*-}

Test

$ d="file-8923489_something.txt"
$ d1=${d%_*}
$ echo $d1
file-8923489
$ echo ${d1##*-}
8923489

$ d="some-other_file-8923489_something.txt"
$ d1=${d%_*}
$ echo $d1
some-other_file-8923489
$ echo ${d1##*-}
8923489

$ d="another_file-8923489_something.txt"
$ d1=${d%_*}
$ echo $d1
another_file-8923489
$ echo ${d1##*-}
8923489



回答3:


Is it possible to do this using operators only, ...

$ filename="file-8923489_something.txt"
$ file=${foo//[^0-9]/}
$ echo $file
8923489

You might want to refer to Shell Parameter Expansion.

Alternatively, you can say:

$ file=$(tr -dc '[[:digit:]]' <<< "$filename")
$ echo $file
8923489


来源:https://stackoverflow.com/questions/19267302/bash-how-to-extract-substring-that-is-surrounded-by-specific-text

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!