how to write a SED script to replace the version code present in a file based on user input using Regex

好久不见. 提交于 2020-05-09 07:16:08

问题


I am taking the version code from user input and trying to replace the existing version code with the new one.

The file which contains version code is named "Version.gradle", it contains

defaultConfig {
    applicationId "com.service_app"
    minSdkVersion rootProject.ext.minSdkVersion
    targetSdkVersion rootProject.ext.targetSdkVersion
    versionCode 1
    versionName "1.0"
}

I am able to get the version from user, but I don not know how to replace the new version code with exiting one. I am using the below pattern to fetch the existing version code.

echo "Enter versionCode"
read versionCode
replacement=$(sed 'versionCode=\"(\\d+)\"' Version.gradle)
replacement=${versionCode}
sed "s/PATTERN/$replacement/g" Version.gradle

Current Output:

command : sed e version.sed
Enter versionCode
2
sed: -e expression #1, char 22: expected newer version of sed
sed: can't read Version.gradle: Permission denied

Expected Output:

In version.gradle file, 2 should replace the already existing version code.


回答1:


First, make sure you have write access to the file.

Then, you may use

sed -i "s/\(versionCode[[:space:]]*\)[0-9]*/\\1${versionCode}/" file

Using FreeBSD sed:

sed -i '' "s/\(versionCode[[:space:]]*\)[0-9]*/\\1${versionCode}/" file

POSIX BRE pattern & replacement details

  • \(versionCode[[:space:]]*\) - Capturing group 1:
    • versionCode - a literal word
    • [[:space:]]* - 0 or more whitespaces
  • [0-9]* - 0 or more digits
  • \1 - Group 1 placeholder, it puts back the value captured in Group 1 back into the resulting string
  • ${versionCode} - the versionCode contents (note the double quotes surrounding the command, they enable variable expansion).

See the online sed Linux demo:

test=' defaultConfig {
    applicationId "com.service_app"
    minSdkVersion rootProject.ext.minSdkVersion
    targetSdkVersion rootProject.ext.targetSdkVersion
    versionCode 1
    versionName "1.0"
}'
echo "Enter versionCode"
read versionCode
echo "$versionCode"
sed "s/\(versionCode[[:space:]]*\)[0-9]*/\1${versionCode}/" <<< "$test"


来源:https://stackoverflow.com/questions/61134401/how-to-write-a-sed-script-to-replace-the-version-code-present-in-a-file-based-on

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!