Search code examples
linuxsed

linux sed how to replace part of a line without breaking indentation in a text file


I would like to solve this issue. I have a file in linux that is going to be later read as a yaml file, so indententation is very important. I would like to find once specific line and replace only part of it.

::: rest of the file :::
first:
    second:
        third:
            variable: [1, 2, 3]
::: rest of the file :::

what I would like to do is replace only the last element of the array. Is it possible to find the pattern ", 3]" and replace it by for example ", 10]" without breaking the indentation ? So far I think the command sed can help, but i did not find a way not to break the structure of the file. What I know for sure that there is

  • only one instance of "variable: " in the file and the numbers in the array could be either integers or float but they are numbers not letters. and i don't know the numbers in advance.

Thanks if you have any pointers.


Solution

  • Use a yaml parser like yq:

    $ yq -i '.first.second.third.variable[-1] = 10' -- file
    $ cat file
    first:
      second:
        third:
          variable: [1, 2, 10]