简体   繁体   中英

sed command to add a line after some pattern

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

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

Works for me with GNU sed:

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

or

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

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"
]

Using sed

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

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"
]

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
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"
] 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM