特定の行を列挙する方法を知りたいです。この場合、括弧付きの行の後の行のみをリストします。
ソースファイル:file.txt
TITLE: hello world
SUBTITLE: document about hello world
[CONTENT 1]
That's a line
Another one
Row
[EXAMPLE]
Example line
[CONTENT 2]
A
B
C
Text, text, text....
望ましい結果:file.txt
TITLE: hello world
SUBTITLE: document about hello world
[CONTENT 1]
1 That's a line
2 Another one
3 Row
[EXAMPLE]
5 Example line
[CONTENT 2]
6 A
7 B
8 C
Text, text, text....
ベストアンサー1
アッ解決策:
awk '/^\[.+\]/{ f=1 }f && $0~/^\w/{ $0=++c FS $0 }!NF{ f=0 }1' file
/^\[.+\]/{ f=1 }
- 括弧を使用して行を一致させ、f
フラグでマークします。f && $0~/^\w/{ $0=++c FS $0 }
- 「括弧を含む」行の後の行にカウンタ値を追加します。!NF{ f=0 }
- 空行と下行は無視します。 (f=0
- リバース動作を示すリセットフラグ)
出力:
TITLE: hello world
SUBTITLE: document about hello world
[CONTENT 1]
1 That's a line
2 Another one
3 Row
[EXAMPLE]
4 Example line
[CONTENT 2]
5 A
6 B
7 C
Text, text, text....