sed 編輯器刪除文字中的空白行
阿新 • 來源:網路 • 發佈:2022-05-18
sed 編輯器刪除文字中的空白行
在文字處理中,一個常見的需求是刪除文字中的空白行。最簡單的情況是刪除文字中的所有空白行。可以使用如下命令:
[email protected]:~/my_learning$ cat file2
This is 1 line.
This is 2 line.
This is 3 line.
This is 4 line.
[email protected]:~/my_learning$ sed '/^$/d' file2
This is 1 line.
This is 2 line.
This is 3 line.
This is 4 line.
[email protected]:~/my_learning$
刪除連續的空白行
如果需要將文字中的連續多個空白行保留為僅有一行,可以使用地址區間來檢查資料流。如下例,地址區間為 /./ 到 /^$/ ,區間的開始地址會匹配任何一個含有至少一個字元的非空白和和一個空白和的地址空間。
[email protected]:~/my_learning$ cat file2
This is 1 line.
This is 2 line.
This is 3 line.
This is 4 line.
[email protected]:~/my_learning$ sed '/./,/^$/!d' file2
This is 1 line.
This is 2 line.
This is 3 line.
This is 4 line.
[email protected]:~/my_learning$
刪除文字開頭的空白行
有時,資料檔案開頭有多個空白行,在進行資料處理時,需要刪除資料流頂部的空白行。下例中,使用地址匹配 /./,$ ,匹配區間從第一個含有字元的行到文字結束都不會刪除。
[email protected]:~/my_learning$ cat file2
This is 1 line.
This is 2 line.
This is 3 line.
This is 4 line.
[email protected]:~/my_learning$ sed '/./,$!d' file2
This is 1 line.
This is 2 line.
This is 3 line.
This is 4 line.
[email protected]:~/my_learning$
刪除結尾的空白行
刪除結尾的空白行,稍微複雜。可以使用如下命令:
sed '{
:start
/^\n*$/{$d; N; b start }
}'
地址模式能夠匹配只含有一個換行符的行。如果匹配到這樣的行,並且其還是最後一行,將使用刪除命令刪除。如果不是最後一行,N 命令會將下一行附加到它後面,分支命令會跳到迴圈起始位置重新開始。
[email protected]:~/my_learning$ cat file2
This is 1 line.
This is 2 line.
This is 3 line.
This is 4 line.
[email protected]:~/my_learning$ sed '{
> :start
> /^\n*$/{$d; N; b start}
> }' file2
This is 1 line.
This is 2 line.
This is 3 line.
This is 4 line.
[email protected]:~/my_learning$
