我想編寫一個 bash 函數,列印文件中匹配的行## mode: org
和之間包含的文字部分,各部分之間有一個空白行。## # End of org
在 之前##
,可以有任意數量的空格。
以下是從中提取資訊的文件範例。
file: test.sh
## mode: org
## * Using case statement
## # End of org
case $arg in
("V")
echo "Author"
;;
(*)
## mode: org
## ** Silent Error Reporting Mode (SERM) in getopts
## *** Detects warnings without printing built-in messages.
## *** Enabled by colon {:} as first character in shortopts.
## # End of org
break
;;
esac
期望的輸出是
* Using case statement
** Silent Error Reporting Mode (SERM) in getopts
*** Detects warnings without printing built-in messages.
*** Enabled by colon {:} as first character in shortopts.
我已經做到了
capture-org ()
{
sed -n '/^ *## mode: org$/,/^ *## # End of org$/s/ *//p' "$1" |
sed 's/^## mode: org$/\n## mode: org/' |
sed '/^## mode: org$/d' | sed '/^## # End of org$/d' | cut -c 3-
}
能以更簡潔的方式完成嗎?
答案1
sed '/^[[:space:]]*## mode: org$/,/^[[:space:]]*## # End of org$/!d; /^[[:space:]]*## mode: org$/d; s/^[[:space:]]*## # End of org$//g; s/^[[:space:]]*## //'
這將刪除開始和結束模式之外的所有內容。然後它將刪除開始模式並用空白行替換結束模式(成為區塊分隔符號)。