[英]Bash: replace substring between quotes that contains any character type
I am trying to edit part of a string using a Bash (version 3.2) script. 我正在尝试使用Bash(3.2版)脚本来编辑字符串的一部分。
For example, in $line 例如,在$ line中
line='<Coordinate text1="0" coordinateIndex="78?907??" anotherID="9098" yetanoherID="1.2.3" xyz:text="abc"/>'
I need to edit the contents of coordinateIndex (which can have any character/any length). 我需要编辑coordinateIndex的内容(可以具有任何字符/任何长度)。 My last attempt (below) doesn't give an error but doesn't solve the problem either:
我的最后尝试(如下)没有给出错误,但也不能解决问题:
echo "${line/coordinateIndex=\"\[(.*)\]\"/coordinateIndex="124"/line}"
I also tried using ")" instead of "]"; 我也尝试使用“)”代替“]”; also .+, among many others.
还有。+等。
The output I am looking for is: 我正在寻找的输出是:
line='<Coordinate text1="0" coordinateIndex="124" anotherID="9098" yetanoherID="1.2.3" xyz:text="abc"/>'
I tried solutions based on 我尝试了基于
Regex Match any string powershell 正则表达式匹配任何字符串powershell
http://unix.ittoolbox.com/groups/technical-functional/shellscript-l/shell-script-to-replace-string-within-double-quotes-4107915 http://unix.ittoolbox.com/groups/technical-functional/shellscript-l/shell-script-to-replace-string-within-double-quotes-4107915
https://superuser.com/questions/515421/using-sed-get-substring-between-two-double-quotes https://superuser.com/questions/515421/using-sed-get-substring-between-two-double-quotes
but I am still unable to solve this. 但我仍然无法解决这个问题。
Any help appreciated, thank you! 任何帮助表示赞赏,谢谢!
It can be done easily with perl
: 使用
perl
可以轻松完成:
#!/bin/bash
str=$(cat << EOF
line='<Coordinate text1="0" coordinateIndex="78?907??" anotherID="9098" yetanoherID="1.2.3" xyz:text="abc"/>'
EOF
)
echo "$str" |perl -pe 's|(coordinateIndex=)".*?"|$1"abc"|g'
Output: 输出:
bash test.sh
line='<Coordinate text1="0" coordinateIndex="abc" anotherID="9098" yetanoherID="1.2.3" xyz:text="abc"/>
You can do it with Bash regex matching. 您可以使用Bash正则表达式匹配来做到这一点。
var=coordinateIndex
value=124
if [[ $line =~ $var=\"([0-9|\?]+)\" ]]; then
echo ${line/$var=\"${BASH_REMATCH[1]}\"/$var=\"$value\"}
fi
They key here is to know which type of characters can be found in between the quotes after coordinateIndex=
. 他们的关键是要知道在
coordinateIndex=
之后的引号之间可以找到哪种类型的字符。 If you just use *
, which matches any character, you'll end up matching and replacing everything up to the final "
in the variable line
. 如果仅使用
*
匹配任何字符,则最终将匹配并替换所有内容,直到变量line
的最后一个"
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.