【发布时间】:2015-05-20 09:00:13
【问题描述】:
我只需要从文本文件的前 6 行中删除空白行。我尝试使用this StackOverflow question 和this file 拼凑一个解决方案,但无济于事。
这是我正在使用的 sed 脚本(别名为 faprep='~/misc-scripts/fa-prep.sed),最后一个命令是失败的:
#!/opt/local/bin/sed -f
# Title Treatments
s|<\(/\?\)h1[^>]*\?>|[\1b]|g # Replace <h1></h1> with [b][/b] for saga titles
s|<\(/\?\)h2[^>]*\?>|[\1i]|g # Replace <h2></h2> with [i][/i] for arc titles
s|</\?h3[^>]*\?>||g # Strip <h3 id=""></h3> out without removing chapter title text
# HTML tag strips & substitutions
s|</\?p>||g # Strip all <p></p> tags
s|<\(/\?\)em>|[\1i]|g # Change <em></em> to [i][/i]
s|<\(/\?\)strong>|[\1b]|g # Change <strong></strong> to [b][/b]
# Character code substitutions
s/&\#822[01];/\"/g # Replace “ and ” with straight double quote (")
s/&\#8217;/\'/g # Replace ’ with straight single quote (')
s/&\#8230;/.../g # Replace … with a 3-period ellipsis (...)
s/&\#821[12];/--/g # Replace — with a 2-hyphen em dash (--)
# Final prep; stripping out unnecessary cruft
/<body>/,/<\/body>/!d # Delete everything OUTSIDE the <body></body> tags
/<\/\?body>/d # Then, delete the body tags :3
# Pay attention to meeeeeeee!!!!
1,6{/./!d} # Remove blank lines from around titles??
这是我从终端运行的命令,它显示最后一行未能从文件的前 6 行中去除空格(当然,在进行了所有其他修改之后):
calyodelphi@dragonpad:~/pokemon-story/compilations $ ch='ch6'; faprep $ch-mmd.html > $ch-fa.txt; head -6 $ch-fa.txt
[b]Hoenn Saga (S1)[/b]
[i]Next City Arc (A2)[/i]
Chapter 6: A Peaceful City Stroll... Or Not
calyodelphi@dragonpad:~/pokemon-story/compilations $
文件的其余部分由第三个标题后的空行和所有由空行分隔的段落组成。我想保留那些空行,这样只有最顶部的标题之间的空行会被剥离。
只是为了澄清几点:这个文件有 Unix 行结尾,并且这些行应该没有空格。即使在显示空白的文本编辑器中查看,每个空白行也只包含一个换行符。
【问题讨论】:
-
疯狂猜测:输入文件是否有 windows 行结尾? (您可能在使用 cygwin 吗?)哦,只是为了确定:这些行中没有空格,是吗?
-
刚刚编辑了我的问题来回答你的问题。 ^..^ 它们是 unix 结尾(Mac OS X),空行仅包含换行符。
-
MacOS X 的 sed 对很多事情都有些挑剔。我想你需要一个分号——试试
1,6{/./!d;},这行得通吗?尽管在这种情况下我预计 sed 会抱怨语法错误。 -
用正则表达式解析 HTML:stackoverflow.com/a/1732454/7552
-
@CalyoDelphi 你会这么认为,但不是。使用第二个 sed 进程是一种解决方案,但我可以制作一些东西来保持它在一个中。稍等片刻。