twohyjr
twohyjr

Reputation: 120

Replace value containing quotes with sed command and regex

I am trying to substitute a new version in my yaml file using sed, but I cannot figure out what I am missing from this statement.

I want to convert

version: "x.x.x"

to

version: "z.z.z"

Here is my current sed Statement:

sed -i "" "s|version: "[[:digit:]].[[:digit:]].[[:digit:]]"\|version: "${VERSION}"|" file.yaml

Upvotes: 1

Views: 555

Answers (3)

Ed Morton
Ed Morton

Reputation: 203229

$ sed 's/\(version: "\)[^"]*/\1'"$VERSION"'/' file
version: "z.z.z"

Upvotes: 0

Marcos Oliveira
Marcos Oliveira

Reputation: 11

sed -i -r "s@version: [0-9]+\.[0-9]+\.[0-9]+@version: ${VERSION}@" file.yaml

Upvotes: 1

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626738

You may use

sed -i "" 's|version: "[[:digit:]]\.[[:digit:]]\.[[:digit:]]"|version: "'"${VERSION}"'"|' file.yaml

To match one or more digits you may use \{1,\} range quantifier after eacg [[:digit:]]:

sed -i "" 's|version: "[[:digit:]]\{1,\}\.[[:digit:]]\{1,\}\.[[:digit:]]\{1,\}"|version: "'"${VERSION}"'"|' file.yaml

Details

  • version: "[[:digit:]]\.[[:digit:]]\.[[:digit:]]" - LHS, matches version:, space, ", a digit, ., a digit, . and a digit (digits if \{1,\} is used)
  • version: "'"${VERSION}"'" - RHS, replacement, replaces with version:, space, ", VERSION variable contents, and a ".

You may slightly shorten the command by using

sed -i "" 's|\(version: "\)[[:digit:]]\(\.[[:digit:]]\)\{2\}"|\1'"${VERSION}"'"|' file.yaml

where \(version: "\) is captured into Group 1 and, inside RHS, \1 is used to insert it back and the repetition of . and digit is done with another group quantified with \{2\} (two times) quantifier.

Upvotes: 1

Related Questions