用bash删除空白部分
我正在寻找一种方法来删除markdown文档中的空白部分,更具体地说,更新日志。用bash删除空白部分
举例来说,如果我有:
## Version
### Added
- something
### Removed
### Changed
- something
### Fixed
我想直到结束:
## Version
### Added
- something
### Changed
- something
注意Fixed
节走了(空,直到文件的结尾)和Version
节仍然存在,因为我只应在###
部分采取行动。
在平原AWK:
#!/usr/bin/awk
BEGIN {
inside_empty_section = "false"
buffer = ""
}
/^$/ { # Add the empty line to the current section buffer or print it
if (inside_empty_section == "true") { buffer = buffer $0 "\n" } else { print $0 }; next }
/^###/ {
# This is the beginning of a new section.
# Either the previous one was empty: just forget its buffer.
# either it was not empty and has already been printed.
# In any case, just start buffering a new empty section.
inside_empty_section = "true"
buffer = $0
next
}
{
# Found a non-empty line: the current section is NOT empty.
# If it was supposed to be empty, print its buffer.
if (inside_empty_section == "true") { print buffer }
inside_empty_section = "false"
print $0
next
}
与启动它:
$ awk -f ./test.awk < plop
## Version
### Added
- something
### Changed
- something
当然,你可以把它更简洁:
awk '/^$/ {if (i) {b=b $0 "\n"} else {print $0 }; next} \
/^###/ {i=1; b=$0; next} {if (i) {print b}; i=0; print $0; next}' < plop
所有解决方案都非常好,但我最喜欢这个。我将'/^### /'修改为'/^### /',以确保只考虑h3标题。 –
awk中溶液:
awk -v RS="###" 'NF>1{ printf "%s%s",(NR==1? "" : RS),$0 }' file
RS="###"
- 考虑###
如记录分隔符NF>1
- 如果记录包含至少2个字段(包括部名)
输出:
## Version
### Added
- something
### Changed
- something
不错,简单而优雅。但是,对于出现在其他地方而不是-3级开始部分的###,绝对不是很健壮(例如'####小节或' - 某些###') –
我同意:好,简单和优雅,但如果一个部分名称可能包含多个单词,则不起作用。 – duthen
在普通的bash:
$ cat foo.sh
#!/usr/bin/env bash
declare -i p=1 # to-print or not-to-print flag
declare w="" # buffer
declare l="" # line
while read l; do
if [[ $l =~ ^###[^#] ]]; then # if new section
((p)) && printf "%s" "$w" # if to-print, print buffer
w="$l"$'\n' # re-initialize buffer
p=0 # reset to-print flag
else
w="$w$l"$'\n' # update buffer
[[ -n $l ]] && p=1 # if non-empty line, set to-print flag
fi
done < $1
((p)) && printf "%s" "$w" # if to-print, print buffer
$ ./foo.sh foo.md
## Version
### Added
- something
### Changed
- something
你可以,如果你的部分和空部分的定义是不完全的读线的两个测试适应我所假设的。
为什么downvoting? –