我有一个名为my.md
的降价文件。它包含一个H1标题和许多其他内容,例如:
# My Title
## Sub title
A lot of text and other stuff here...
我想做的是我想在 H1 标题行之后插入一行。要使文件如下所示:
# My Title
(my text)
## Sub title
A lot of text and other stuff here...
我想在#
之后使用 Sed,但问题是它直接将其插入#
符号之后。虽然我实际上希望它单独处于新行中。不在同一行。
有什么想法吗?
sed
具有附加(a
(命令,用于在匹配的行后附加文本。因此,您可以将该行与 h1 匹配(从单个单#
开始(,然后同样放置所需的文本:
sed '/^#[^#]/a (my text)' file.txt
例:
% cat file.txt
# My Title
## Sub title
A lot of text and other stuff here...
% sed '/^#[^#]/a (my text)' file.txt
# My Title
(my text)
## Sub title
A lot of text and other stuff here...
您可以使用sed
:
s='(my text)'
sed "/^# /a\
\
$s
" file
# My Title
(my text)
## Sub title
A lot of text and other stuff here...
或使用awk
:
awk -v s="$s" 'p{printf "n%sn", s; p=0} /^# /{p=1} 1' file
# My Title
(my text)
## Sub title
A lot of text and other stuff here...
这可能对你有用(GNU sed(:
cat <<! | sed '/^#s/r /dev/stdin' file
$DISPLAY
!
这会将此处文档附加到文件中与 sed 匹配的地址。
也尝试关注一次,让我知道这是否有帮助。
awk -v my_text="your_text_here..." '{printf("%sn",/^##/?my_text ORS ORS $0:$0)}' Input_file
说明:创建一个名为 my_text 的变量,其值将是要插入的文本。现在在这里使用 printf,并在检查条件中检查是否有任何行从 ## 开始,然后打印变量,然后 2 个新行 (ORS( 输出记录分隔符,其默认值将是新行,然后是当前行,如果任何行不以 ## 开头,则简单地打印它。