bash sed 替换双引号内的内容

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30637112/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 13:07:26  来源:igfitidea点击:

sed replace content within double quotes

regexbashsed

提问by mach

I need to replace the versionName in a xml file from a shell script using sed.

我需要使用 sed 从 shell 脚本替换 xml 文件中的 versionName。

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.example.sed"
    android:versionCode="1"
    android:versionName="UNKNOWN VERSION NAME">

I've gotten so far as to search for a line containing versionName but how to tell sed to replace everything within the double quotes coming directly after versionName?

我已经搜索了包含 versionName 的行,但是如何告诉 sed 替换 versionName 之后直接出现的双引号内的所有内容?

sed -i .old '/versionName/ s/WHAT TO WRITE?/NEW VERSION NAME/' AndroidManifest.xml

采纳答案by lcd047

Replace not-", like this:

替换not-",像这样:

sed -i .old '/android:versionName/ s/="[^"][^"]*"/="NEW VERSION NAME"/' AndroidManifest.xml

回答by Lungang Fang

Considering the nature of xml and the version number, it is actually very safe to use a simpler command:

考虑到xml的性质和版本号,使用更简单的命令其实是很安全的:

sed -i '/versionName/s/".*"/"NEW VERSION NAME"/' AndroidManifest.xml

P.S. in my opinion, it is very important to be able to simplify your shell script based on specific circumstances and reasonable assumptions.

PS在我看来,能够根据具体情况和合理假设简化你的shell脚本是非常重要的。

回答by NeronLeVelu

sed 's/\([[:blank:]]android:versionName="\)[^"]*"/Your New Value"/' YourFile
  • assuming that all section that have android:versionNamewill be changed
  • with GNU sed still better with replacing [[:blan:k]]by \(^\|[[:blank:]]\)(and a -iif direct modification avoiding temporary file)
  • 假设所有的部分都android:versionName将被更改
  • 使用 GNU sed 替换[[:blan:k]]为更好\(^\|[[:blank:]]\)(以及-i避免临时文件的if 直接修改)