简体   繁体   English

sed 命令在某个模式之后添加一行

[英]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现在如何添加命令(使用 sed 或 awk 的 shell),我需要以下输出

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我试过的很少 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很挑剔,但以下每个都应该工作:

$ 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:使用 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

$ 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.然后捕获第 1 组中的换行符和前导空格。

In the replacement use your text surrounded by double quotes and a backreference to group 1 to keep the indenting the same.在替换中,使用双引号括起来的文本和对第 1 组的反向引用以保持缩进相同。

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):这可能对您有用(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.在第 2 行,复制该行,从现有文本开始缩进的地方替换所需的字符串,打印修改后的行并恢复原始行。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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