12

複数のセクションを含むテキスト ファイルがあり、それらのセクションの 1 つを印刷したいと考えています。

ファイルの一部は次のようになります

3. line 3
4. line 4

## Screenshots ##

1. line 1
2. line 2
3. line 3
4. line 4

## Changelog ##

3. line 3
4. line 4

## Screenshots ##これから、次のセクションの開始までの間のすべての行を取得したいと思います。次のセクションは ですが## Changelog ##、何でもかまいません。したがって、信頼できる唯一のことは、それが で始まるということ##です。

別のスレッドから、次のコードを見つけました

sed -e "H;/${pattern}/h" -e '$g;$!d' $file

私が変更した

sed -e "H;/## Screenshots ##/h" -e '$g;$!d' readme.md

現在、 から始まるすべての行を取得します## Screenshots ##が、ファイルの最後までのすべての行を出力します。

sed次に、それを別のようなものにパイプしました

sed -e "H;/## Screenshots ##/h" -e '$g;$!d' readme.md | sed "/^##/q" 

しかし、今は印刷のみです

## Screenshots ##

スクリーンショットセクションのすべての行を印刷できる方法はありますか?

4

4 に答える 4

27
awk '/pattern/{p=1;print;next} p&&/^##/{p=0};p' file

例として「スクリーンショット」を取り上げます。

kent$  awk '/^## Screenshot/{p=1;print;next} p&&/^##/{p=0};p' file
## Screenshots ##

1. line 1
2. line 2
3. line 3
4. line 4

編集説明を追加

awk '/^## Screenshot/{p=1;print;next} : if match pattern, set p=1,print the line,read next line,(stop processing following scripts)
p&&/^##/{p=0}                         : if p==1 and match /##/ again (next section), set p=0
;p' file                              : if p==1, print the line

シードのみ

sed -n '/## Screensh/,/##/{/Scree/{p;n};/##/{q};p}' file

EDIT2 sed cmd に説明を追加

-n                 -> not print
'/## Screen/, /##/ -> match range, I guess you knew it already
{                  -> if in this range
    /Scree/        -> and line matches /Screenshot/
        {p;n};     -> do print line, and read next row (skip doing rest processing)
    /##/           -> if line matches "##"
        q;         -> quit, we have done all printing
    p              -> if we come to here, print the line
}
于 2013-05-16T12:37:43.057 に答える
10

sed -n '/## Screenshots ##/,/##/p' readme.md

## Screenshots ##これは、次##が見つかるまでから印刷を開始します。##最後の一致が必要ない場合、最も簡単なのは

sed -n '/## Screenshots ##/,/##/p' readme.md |head -n-1

于 2013-05-16T12:39:08.593 に答える
5

おかしい

これは、次の方法でより簡単かつ一般的に行うことができますawk

awk '/^##/ { p-- } /^## Screenshots/ { p=1 } p>0' infile

1 つのセクションのみが必要な場合は、次のようになります。

awk '/^##/ { p=0 } /^## Screenshots/ { p=1 } p' infile

出力:

## Screenshots ##

1. line 1
2. line 2
3. line 3
4. line 4

説明

/^##/ { p-- }               # subtract one from the section counter
/^## Screenshots/ { p=1 }   # set section counter if current line has Screenshot 
p>0                         # print line if section counter greater than 0

シード

sed -n '/^## Screenshots/,/^##/p' infile | sed '$d'
于 2013-05-16T12:26:47.847 に答える