简体   繁体   中英

How to fetch a string which is in between a (fixed) pattern using shell scripting?

I have to fetch the 'string' which is stored in between the pattern '[ ]'. Example is given below [string]_someOtherString

Length of string to be fetched is not fixed. I would appreciate if you can help me do this. I dont want to use the cut command multiple times. I want to see if there is a simple and elegant way. Its good if you can suggest me multiple ways to solve this(helps me learn and compare different techniques).

One way would be to use grep :

$ grep -oP '(?<=\[).*(?=\])' <<< '[string]_someOtherString'
string

using python you can do something like:

import re

stg = '[string]_someOtherString'
print re.findall('\[([^\[\]]+)\]', stg)

or in the shell:

python -c "import re, sys; print re.findall('\[([^\[\]]+)\]', sys.argv[1])" '[string]_someOtherString'

and if you know that you only have one mathcing string:

python -c "import re, sys; print re.findall('\[([^\[\]]+)\]', sys.argv[1])[0]" '[string]_someOtherString'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM