Home > Mobile >  sed command to add a line after some pattern
sed command to add a line after some pattern

Time:06-24

I have a file (content below)

name = [
    "victor",
    "linda",
    "harris",
    "sandy"
] 

Now how to i add a command (shell using sed or awk) and i need below output

name = [
    "NEW INPUT HERE",
    "victor",
    "linda",
    "harris",
    "sandy"
] 

I have tried multiple ways but not able to achieve it. Few of them what i tried sed '2a'$'\n'' "NEW INPUT HERE", ' filename

I am able to get add it but not giving new line after my input

CodePudding user response:

Some sed are finicky, but each of the following should work:

$ sed -e '1a\
    "NEW INPUT HERE",
' input-file

$ sed -e $'1a\\\n    "NEW INPUT HERE",\n' input-file # Bashism

CodePudding user response:

Using sed

$ sed '2{h;s/[[:alpha:]][^"]*/NEW INPUT HERE/};2G' input_file
name = [
    "NEW INPUT HERE",
    "victor",
    "linda",
    "harris",
    "sandy"
]

CodePudding user response:

Works for me with GNU sed:

sed '2i\    "NEW INPUT HERE",'

or

sed '1a\    "NEW INPUT HERE",'

CodePudding user response:

This will just use for the new line whatever indenting you already use for the existing 2nd line:

$ awk -v new='"NEW INPUT HERE",' 'NR==2{orig=$0; sub(/[^[:space:]].*/,""); print $0 new; $0=orig} 1' file
name = [
    "NEW INPUT HERE",
    "victor",
    "linda",
    "harris",
    "sandy"
]

CodePudding user response:

Another option is to match the [ and the next line.

Then capture the newline and leading spaces in group 1.

In the replacement use your text surrounded by double quotes and a backreference to group 1 to keep the indenting the same.

sed -E '/\[/{N;/(\n[[:blank:]] )/{s//\1"NEW INPUT HERE",\1/}}' file

Output

name = [
    "NEW INPUT HERE",
    "victor",
    "linda",
    "harris",
    "sandy"
]

CodePudding user response:

awk -v str='"NEW INPUT HERE",' '
    /name/{
           print; 
           getline;                                 # get first element (victor)
           le=length($0)-length($1);                # calculate first element ident  
           printf "%*s%s \n%s\n", le, " ", str, $0;
           next
}1' file

name = [
    "NEW INPUT HERE", 
    "victor",
    "linda",
    "harris",
    "sandy"
] 

CodePudding user response:

This might work for you (GNU sed):

sed '2{h;s/\S.*/"NEW INPUT HERE",/p;g}' file

On line 2, make a copy of the line, substitute the required string starting where existing text starts indented, print the amended line and reinstate the original line.

Another solution using a regexp for the address line:

sed '/name = \[/{n;h;s/\S.*/"NEW INPUT HERE",/p;g}' file
  • Related