【发布时间】:2014-09-08 20:27:21
【问题描述】:
我正在尝试使用 Bash(3.2 版)脚本编辑字符串的一部分。
例如,在 $line 中
line='<Coordinate text1="0" coordinateIndex="78?907??" anotherID="9098" yetanoherID="1.2.3" xyz:text="abc"/>'
我需要编辑坐标索引的内容(可以有任何字符/任何长度)。我的最后一次尝试(如下)没有给出错误但也没有解决问题:
echo "${line/coordinateIndex=\"\[(.*)\]\"/coordinateIndex="124"/line}"
我也试过用“)”代替“]”;还有 .+ 等等。
我正在寻找的输出是:
line='<Coordinate text1="0" coordinateIndex="124" anotherID="9098" yetanoherID="1.2.3" xyz:text="abc"/>'
我尝试了基于
的解决方案Regex Match any string powershell
https://superuser.com/questions/515421/using-sed-get-substring-between-two-double-quotes
但我仍然无法解决这个问题。
任何帮助表示赞赏,谢谢!
【问题讨论】:
-
我相信您正在寻找的是字符否定类
[^"],它将捕获任何不是"的东西。用法示例:echo "${line/coordinateIndex=\"\[^\"\]*\"/coordinateIndex="124"/line}" -
感谢您的回答;不幸的是,它对我不起作用......
-
方括号转义有什么原因吗?它不应该读取 echo "${line/coordinateIndex=\"[^\"]*\"/coordinateIndex=\"124\"/line}"? 请注意在替换中 124 周围的引号中添加了转义符。
-
这实际上将坐标索引更改为124!但不会复制该行的其余部分。我得到输出:
-
你不能使用匹配任何字符的'*'。你需要 extglob,如下所示: shopt -s extglob; echo "${line//coordinateIndex=\"*([^\"])\"/coordinateIndex=\"124\"}";