Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading