简体   繁体   中英

Bash - Find and replace regex with another string

I have the following string libVersion = '1.23.45.6' and I need to replace 1.23.45.6 with 1.23.45.7 .

Obviously the version could be any number with similar format (it does not have to be 4 numbers).

I tried to use the following but doesn't work

echo "libVersion = '1.23.45.6'" |sed "s/([0-9\\.]+)/1.23.45.7/g"

Basic sed, ie sed without any arguments uses BRE (Basic Regular Expression). In BRE , you have to escape + , to bring the power of regex + which repeats the previous token one or more times, likewise for the capturing groups \\(regex\\)

echo "libVersion = '1.23.45.6'" | sed "s/[0-9.]\+/1.23.45.7/"

You may also use a negated char class to replace all the chars exists within single quotes.

echo "libVersion = '1.23.45.6'" | sed "s/'[^']*'/'1.23.45.7'/"

Since the replacement should occur only one time, you don't need a g global modifier.

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