Home > database >  Change indented multiline string in file in terminal
Change indented multiline string in file in terminal

Time:05-13

i want to change multiline string within particular marks that is indented in file, example looks like this:

    non_important_array: [
    text
    ],
    important_array: [
    text1,
    text2,
    text3
    ],
    non_important_array: [
    text
    ],

my goal is to be able to replace important_array with my multiline string

    my_array: [
    my_text1,
    my_text2
    ],

so i would like to have it like so:

    non_important_array: [
    text
    ],
    my_array: [
    my_text1,
    my_text2
    ],
    non_important_array: [
    text
    ],

but there could be also a variation, and it will look like this:

    non_important_array: [text],
    important_array: [text1,text2,text3],
    non_important_array: [text],

and the output should be looking similar as expected above

    non_important_array: [text],
    my_array: [
    my_text1,
    my_text2
    ],
    non_important_array: [text],

Right now im trying to make this work with sed, but it's taking last occurance of ] and i dont know how to correct that

sed -i '' '/\s*important_array.*/,/\]/c\
    my_array: [\
    my_text1,\
    my_text2\
    ],' file.txt

Thanks!

EDIT:

  • one liner would be much appreciated
  • i want to replace it inplace, to have the same file modified

CodePudding user response:

Using any POSIX awk:

$ cat tst.awk
NR == FNR {
    new = new $0 ORS
    next
}
/^[[:space:]]*important_array:[[:space:]]*\[/ {
    inBlock = 1
    printf "%s", new
}
inBlock {
    if ( /^[[:space:]]*],/ ) {
        inBlock = 0
    }
    next
}
{ print }

$ awk -f tst.awk file2 file1
    non_important_array: [
    text
    ],
    my_array: [
    my_text1,
    my_text2
    ],
    non_important_array: [
    text
    ],

CodePudding user response:

sulution 1: awk script:

 awk '{sub("[[:space:]]important_array:"," my_array:")}1' ORS="]," RS="]," input.txt

Output:

non_important_array: [
text
],
my_array: [
text1,
text2,
text3
],
non_important_array: [
text
],

sulution 2: awk script:

 awk '
  BEGIN{ORS="],\n"; RS="],"; FS="\n"; OFS=" "}
  {
    sub("[[:space:]]important_array:"," my_array:");
    gsub("[[:space:]] "," ");
    $1=$1;
 }1' input.txt

Output:

 non_important_array: [ text ],
 my_array: [ text1, text2, text3 ],
 non_important_array: [ text ],

CodePudding user response:

First test without the -i flag.
I think your problem is \s*, any number of whitespace, so also matches non_.
When you wan to use sed, try

sed -r '/\s important_array.*/,/\]/c\
  my_array: [\
  my_text1,\
  my_text2\
  ],' file.txt
  • Related