简体   繁体   中英

Regex with sed using quotation mark

I need to change part of text in my file. I try to write a script in bash for update my PATH which contains other/old JAVA_HOME. My regex should find part of text which contains path like below and change it with sed command.

/**/jdk/jdk.*/bin

I made regex on:

. bash_env

JAVA_HOME="/opt/jdk/jdk1.8.0_151" 
PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/snap/bin:/opt/jdk/jdk1.8.0_151/bin:example/not/for/change/bin"

expected output

JAVA_HOME="/opt/jdk/jdk1.8.0_151" 
PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/snap/bin:CHANGED:example/not/for/change/bin"

sed command

sed -r 's#([/])[^\/]*([/]jdk[/]jdk).*?([/]bin)#CHANGED#g' ~/.bash_env

Question
I tried a lot of variations with my sed and regex but it doesn't work or change all paths without stopping on first /bin. I think it's problem with questions mark but maybe someone can give me an advice ? Or help with write regex for sed?

UPDATE.1 Example when my solution doesn't work

example .bash_env

PATH="/usr/local/sbin:/opt/jdk/jdk1.8.0_151/bin:/example/not/jdk/for/change/bin"

my sed

sed -r 's#([/])[^\/]*([/]jdk[/]jdk).*?([/]bin)#CHANGED#g' ~/.bash_env

given result

PATH="/usr/local/sbin:CHANGED"

expected result

PATH="/usr/local/sbin:CHANGED:/example/not/jdk/for/change/bin"

Regex (with sed) should change word which:
- starts with '/'
- doesn't contain ':'
- contains 'jdk/jdk'
- ends with '/bin'

You can try this sed

echo $PATH | sed 's/\([^:]*\)/CHANGED/8'

I think the search path isn't always at the same place so try this one.

echo $PATH | sed 's#\(.*\)\(:/.*jdk[^:]*\)\(:.*\)#\1:CHANGED\3#'

You can test this one :

 echo $path | sed 's#\(.*\)\(:*\)\(/.*/jdk/jdk[0-9._]*/bin\)\(:*\)\(.*\)#\1\2CHANGED\4\5#'

I try with the start position, with the end position and in the middle.

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