简体   繁体   中英

Find and replace part of a string using bash in an XML file

I am new to bash scripting and was looking into what kid of command will help me replace a specific string in an xml file.

The string looks like

uri='file:/var/lib/abc/cde.repo/r/c/e/v/1.1/abc-1.1.jar'

Should be replaced with

uri='file:/lib/abc-1.1.jar'

The strings vary as the jars vary too. First part of the string "file:/var/lib/abc/cde.repo/r/" is constant and is across all strings. The 2nd half is varying

This needs to be done across entire file. Please note that replacing one is easier then doing it for each an every string that varies. I am trying to look for solution to do it in one single command.

I know we can use sed but how? Any pointers are highly appreciated

Thanks

With sed :

sed "s~uri='file:/var/lib/abc/cde.repo/r/c/e/v/1\.1/abc-1.1.jar~uri='file:/lib/abc-1\.1\.jar'~g"

Basically it is:

sed "s~pattern~replacement~g"

where s is the command substitute and the trailing g means globally. I'm using ~ as the delimiter char as this helps to avoid escaping all that / in the paths. (thanks @Jotne)


Update: In order to make the regex more flexible, you may try this:

sed 's~file.*/\(.*\.jar\)\(.*\)~file:///lib/\1\2~' a.txt 

It searches for file: ... .jar links, grabs the name of the jar file and builds the new links.

Using awk you can do:

awk -F/ '/file:\/var\/lib\/abc\/cde.repo\/r/ {print $1,$3,$NF}' OFS=/ file
uri='file:/lib/abc-1.1.jar'

Static URL, but changing file name.

You do not need to use sed or even awk . You could simply use basename :

prefix='file:/lib/'
uri='file:/var/lib/abc/cde.repo/r/c/e/v/1.1/abc-1.1.jar'
result="${prefix}$(basename ${uri})"
echo ${result}

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