简体   繁体   中英

search and replace substring in string in bash

I have the following task: I have to replace several links, but only the links which ends with .do

Important: the files have also other links within, but they should stay untouched.

<li><a href="MeinKonto.do">Einstellungen verwalten</a></li>

to

<li><a href="<s:url action='MeinKonto'/>">Einstellungen verwalten</a></li>

So I have to search for links with .do, take the part before and remember it for example as $a , replace the whole link with

<s:url action=' '/>

and past $a between the quotes.

I thought about sed, but sed as I know does only search a whole string and replace it complete. I also tried bash Parameter Expansions in combination with sed but got severel problems with the quotes and the variables.

cat  ./src/main/webapp/include/stoBox2.jsp | grep -e '<a href=".*\.do">' | while read a;
do
    b=${a#*href=\"};
    c=${b%.do*};
    sed -i 's/href=\"$a.do\"/href=\"<s:url action=\'$a\'/>\"/g' ./src/main/webapp/include/stoBox2.jsp;
done;

any ideas ?

Thanks a lot.

Try this one:

sed -i "s%\(href=\"\)\([^\"]\+\)\.do%\1<s:url action='\2'/>%g" \
    ./src/main/webapp/include/stoBox2.jsp;

You can capture patterns with parenthesis ( \\(,\\) ) and use it in the replacement pattern.
Here I catch a string without any " but preceding .do ( \\([^\\"]\\+\\)\\.do ), and insert it without the .do suffix ( \\2 ).

There is a / in the second pattern, so I used % s to delimit expressions instead of traditional / .

sed -i  sed 's#href="\(.*\)\.do"#href="<s:url action='"'\1'"'/>"#g' ./src/main/webapp/include/stoBox2.jsp

Use patterns with parentheses to get the link without .do , and here single and double quotes separate the sed command with 3 parts (but in fact join with one command) to escape the quotes in your text.

 's#href="\(.*\)\.do"#href="<s:url action='

 "'\1'"

 '/>"#g'

parameters -i is used for modify your file derectly. If you don't want to do this just remove it. and save results to a tmp file with > tmp .

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