1

I'm doing the following sed

sed -i {/comment : "Blabla" ;/a leakage_power_unit : "1nW";} $file

After the line "comment : "Blabla" ;" I want to add "leakage_power_unit : "1nW"" but I want to add some spaces before the string. The result should be " leakage_power_unit : "1nW"" but sed is ignoring whitespaces.

I have an alternative which is using the substitute command but the solution is not pretty and this way above is cleaner and more understandable.

So my question is how can I add the spaces with /a?

sed -i {/comment : "Blabla" ;/a     leakage_power_unit : "1nW";} $file

Including empty spaces after "/a" doesn't work

sed -i {s/comment : "Blabla" ;/comment : "Blabla" ;\n  leakage_power_unit : "1nW";/g} $file

works but the expression can be confusion for others.

Cyrus
  • 84,225
  • 14
  • 89
  • 153
miguelfcp
  • 27
  • 5

2 Answers2

1

Whitespace after the a,i or c options are ignored unless \ is added to prevent them from being ignored.

Taking that into account, the following change to your code should now include the whitespace as well as creating a backup of the original file with .bak extension

$ sed -i.bak '/comment : "Blabla" ;/a\     leakage_power_unit : "1nW";' $file
HatLess
  • 10,622
  • 5
  • 14
  • 32
1

What exactly works depends on which version of sed you are using. The syntax of the a command in particular is not properly standardized, and so what works on e.g. Linux will fail on a Mac, and sometimes vice versa.

The lack of quoting and the unnecessary use of braces in your examples are somewhat distracting; but try adding a backslash before the first significant space.

sed -i '/comment : "Blabla" ;/a \  leakage_power_unit : "1nW";' "$file"

Notice also When to wrap quotes around a shell variable?

Works on Linux; demo: https://ideone.com/TA7gNI

On MacOS (or BSD-based Unix platforms generally) you need a backslash and a newline after a, and the next line is the text to insert.

For a portable solution, perhaps switch to Awk or Perl instead. Awk doesn't portably support anything like the -i option of sed, though GNU Awk has an -i inplace extension; Perl, of course, is not formally portable at all, but you will find that it is de facto available in most places in practice.

tripleee
  • 175,061
  • 34
  • 275
  • 318