pcregrepは周囲のスペースがある行を探します。

pcregrepは周囲のスペースがある行を探します。

(マークダウンなので)で始まるタイトルがあり、次の#2つの規則があります。

  • タイトル#)がなければならない正確に改行文字を含む上の2行、下の1行
  • サブタイトル#####など)が必要です正確に上の空白行と下の空白行。
  • タイトルは字幕より優先する必要があります。 (2つのルールが競合する場合は、タイトル形式を使用して字幕を無視します。)

メモ:私はこれら3つの制限を満たさないすべてのタイトルを見つけようとしています。

良いタイトルと悪いタイトルの例は次のとおりです。

some text 
# Title     | BAD 

## Subtitle | Good (Has two spaces below, is needed for next main title)


# Title     | Good

## Subtitle | Bad
text  

# Title     | Bad

text

正規表現で遊んで、次のような表現を思い出しました。

メインタイトル:正規表現

((?<=\n{4})|(?<=.\n{2})|(?<=.\n))(# .*)|(# .*)(?=(\n.|\n{3}(?!# )|\n{4}))

サブタイトル:正規表現

'((?<=\n{3})|(?<=.\n))(##+.*)|(##+.*)(?=\n.|\n{3}(?!# )|\n{4}.)'

しかし、私を本当に混乱させるのは、彼らが一緒に働かないということですpcregrep。私が実行したいコマンドは次のとおりですpcgrep(完全性のため)。

$ pcregrep -rniM --include='.*\.md' \
     '((?<=\n{3})|(?<=.\n))(##+.*)|(##+.*)(?=\n.|\n{3}(?!# )|\n{4}.)' \
     ~/Programming/oppgaver/src/web

1つのファイルだけを検索しようとすると、うまくいきません。

私に何の問題もあるのか?正規表現、それともバグのある実装ですか?

ベストアンサー1

このソリューションは誤ったヘッダーをすべて修正します。

sed -r '
    :loop; N; $!b loop

    s/\n+(#[^\n]+)/\n\n\1/g

    s/(#[^\n]+)\n+/\1\n\n/g

    s/\n+(#[^\n#]+)/\n\n\n\1/g
' input.txt;

追加コメント:

sed -r '
    ### put all file into the pattern space,
    # in other words, merge all lines into one line
    :loop; N; $!b loop;

    ### first traversal of the pattern space
    # searches the line with "#" sign (all cases matches - Titles, SubTitles, etc),
    # takes all its upper empty lines
    # and converts them to the one empty line 
    s/\n+(#[^\n]+)/\n\n\1/g;


    ### second traversal of the pattern space
    # again, searches the line with "#" sign, take all its bottom empty lines
    # and converts them to the one empty line 
    s/(#[^\n]+)\n+/\1\n\n/g;

    ### third traversal of the pattern space
    # searches the single "#" sign (Titles only),
    # takes all its upper newlines (at this moment only two of them are there,
    # because of previous substitutions) 
    # and converts them to three newlines 
    s/\n+(#[^\n#]+)/\n\n\n\1/g
' input.txt

入力する

text
# Title
## SubTitle
### SubSubTitle
# Title
## SubTitle
text
### SubSubTitle
# Title
# Title
# Title
## SubTitle
### SubSubTitle

出力

text


# Title

## SubTitle

### SubSubTitle


# Title

## SubTitle

text

### SubSubTitle


# Title


# Title


# Title

## SubTitle

### SubSubTitle

おすすめ記事