英文:
Delete a paragraph from a file using sed
问题
# Title1
line 1
line 2
line 3
# Title2
line 1
line 2
line 3
我想要能够通过搜索标题来删除其中一个段落。我需要删除标题,接下来的一行,然后删除后续的每一行,直到遇到空行。
期望的输出是:
# Title2
line 1
line 2
line 3
我正在阅读关于使用 {} 将多个命令组合在一起的文章,但似乎无法弄清语法。
cat markdown.md | sed '/^# Title1.*/,+1d {/^\s*$/d}'
我想这将删除以'# Title1'开头的行,然后使用,+1d删除接下来的一行,然后删除后续的行,直到出现空行,但是我看到以下错误:
sed: 1: "/^# Title1.*/,+1d { ...": d 命令末尾有多余的字符
我尝试了一些变化,但没有成功。任何帮助将不胜感激!
英文:
I have a markdown file that looks something like this:
markdown.md
# Title1
line 1
line 2
line 3
# Title2
line 1
line 2
line 3
I'd like to be able to delete one of the paragraphs by searching for the title. I would need to delete the title, the following line, and then every subsequent line that is not blank.
The desired output would be:
# Title2
line 1
line 2
line 3
I was doing some reading about using {} to group multiple commands together but I can't seem to quite get the syntax right.
cat markdown.md | sed '/^# Title1.*/,+1d {/^\s*$/d}'
My thinking was this would delete the line beginning with '# Title1', then the following line with ,+1d, then subsequent lines until a blank line, but i see the following error:
sed: 1: "/^# Title1.*/,+1d { ...": extra characters at the end of d command
I've tried a few variations but no luck. Any help would be appreciated!
答案1
得分: 2
这是一种让我希望有一个略有不同工具的sed难题。
sed -n -e '/Title1/!{p;d;};n;' -e ':a' -e 'n;/./ba'
大致翻译为:“不要打印任何东西。如果不包含 'Title1',那么好吧,打印它,然后重新开始下一行。但如果它包含 'Title1',那么获取下一行(这将是空行),进入循环,并继续获取新行,直到遇到下一个空行。”
英文:
This is the kind of sed puzzle that makes me wish for a slightly different tool.
sed -n -e '/Title1/!{p;d;};n;' -e ':a' -e 'n;/./ba'
Loosely translated: "Don't print anything. If it doesn't contain 'Title1', then all right, print it, then start over with the next line. But if it does contain 'Title1', then grab the next line (which will be blank), enter a loop, and keep grabbing new lines until you come to the next empty line."
答案2
得分: 1
使用GNU的sed
:
$ sed -z 's/# Title1[^#]*//' input_file
# Title2
line 1
line 2
line 3
英文:
Using GNU sed
$ sed -z 's/# Title1[^#]*//' input_file
# Title2
line 1
line 2
line 3
答案3
得分: 1
这可能适用于您(GNU sed):
sed '/^# /h;G;/\n# Title1/!P;d' file
如果一行以 #
开头,请复制。
将副本附加到每一行,如果该行不包含 \n# Title1
,则将其打印出来。
删除所有行。
另一种方法:
sed '/^# Title1/{:a;N;/\n#/!s/\n//;ta;D}' file
英文:
This might work for you (GNU sed):
sed '/^# /h;G;/\n# Title1/!P;d' file
If a line begins #
, make a copy.
Append the copy to each line and if that line does not contain \n# Title1
, print it.
Delete all lines.
Alternative:
sed '/^# Title1/{:a;N;/\n#/!s/\n//;ta;D}' file
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论