[英]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. 我是bash脚本的新手,一直在研究什么样的命令将帮助我替换xml文件中的特定字符串。
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.
字符串“ file:/var/lib/abc/cde.repo/r/”的第一部分是恒定的,并且贯穿所有字符串。 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? 我知道我们可以使用sed,但是如何使用? Any pointers are highly appreciated
任何指针都受到高度赞赏
Thanks 谢谢
With sed
: 与
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. 其中
s
是命令替换,尾随g
表示全局。 I'm using ~
as the delimiter char as this helps to avoid escaping all that /
in the paths. 我将
~
用作定界符char,因为这有助于避免转义所有/
路径。 (thanks @Jotne) (感谢@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. 它搜索
file: ... .jar
链接,获取jar文件的名称并建立新链接。
Using awk
you can do: 使用
awk
您可以执行以下操作:
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
. 您无需使用
sed
甚至awk
。 You could simply use basename
: 您可以简单地使用
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}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.