Tuesday, July 26, 2022

[SOLVED] Replace string bash script with sed

Issue

I am (unsuccessfully) trying to change my log format file. I have input text which include:

VERSION = [1.1, 2.2, 3.3, 4.4]

Cuz my client use split style with " delimiter so I want to use sed command to convert input into:

VERSION = [ "1.1", "2.2", "3.3", "4.4" ]

I have tried this but it not works:

sed 's/^\(VERSION = \[\).*\(\]$\)/\1\", \"\2/'

Can anyone help me, thanks in advance!


Solution

Better you match number and enclose them with double quotes in replacement:

s='VERSION = [1.1, 2.2, 3.3, 4.4]'
sed -E '/^ *VERSION =/ { s/[0-9]+(\.[0-9]+)?/"&"/g; s/\[/& /; s/\]/ &/; }' <<< "$s"

VERSION = [ "1.1", "2.2", "3.3", "4.4" ]

Here:

  • /^[[:blank:]]*VERSION =/: Matches a line starting with optional spaces followed by VERSION = text
  • [0-9]+(\.[0-9]+)?: Matches an integer number or floating point number
  • "&": Wraps matched string with "
  • s/\[/& /: Add a space after [
  • s/\]/ &/: Add a space before ]


Answered By - anubhava
Answer Checked By - Robin (WPSolving Admin)