[英]Sed, insert a line after a pattern match and ignore any commented line strating with #
I would like to insert a line after a pattern match and ignore any commented line ( starting with '#' ) in Bash shell using sed
. 我想在模式匹配后插入一行,并使用
sed
忽略Bash shell中的任何注释行(以'#'开头)。
Here is an example: inserting a new line after pattern
: 这是一个示例:在
pattern
之后插入新行:
Input file: 输入文件:
foo
Art
street
#pattern
foo
pattern
color
Output: 输出:
foo
Art
street
#pattern
foo
pattern
NEW LINE HERE
color
With sed
: 与
sed
:
$ cat file
foo
Art
street
#pattern
foo
pattern
color
$ sed '/^[^#]*pattern/ a NEW LINE HERE' file
foo
Art
street
#pattern
foo
pattern
NEW LINE HERE
color
尝试跟随一次。
awk '/pattern/ && !/#/{print $0 ORS "NEW LINE HERE";next} 1' Input_file
Another approach with sed: sed的另一种方法:
sed 's/^pattern.*/&\nNEW LINE HERE/' file
Replace line starting with pattern
with matching line( &
) followed by new line( \\n
) and desired string. 将
pattern
开头的行替换为匹配的行( &
),然后是新行( \\n
)和所需的字符串。
Using awk
: 使用
awk
:
awk -v line='NEW LINE HERE' -v pat='pattern' '1; $0 ~ pat && !/^[ \t]*#/{print line}' file
foo
Art
street
#pattern
foo
pattern
NEW LINE HERE
color
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.