Bash

從文件中刪除段落

  • April 6, 2020

我有一個file.php像這樣的文件():

...
Match user foo
       ChrootDirectory /NAS/foo.info/
       ForceCommand internal-sftp
       AllowTcpForwarding no
       GatewayPorts no
       X11Forwarding no



Match user bar
       ChrootDirectory /NAS/bar.co.uk/
       ForceCommand internal-sftp
       AllowTcpForwarding no
       GatewayPorts no
       X11Forwarding no



Match user baz
       ChrootDirectory /NAS/baz.com/
       ForceCommand internal-sftp
       AllowTcpForwarding no
       GatewayPorts no
       X11Forwarding no

我正在嘗試編寫一個 bash 腳本來刪除其中一個段落。


所以說我想foofile.php. 執行腳本後,它將如下所示:

...
Match user bar
       ChrootDirectory /NAS/bar.co.uk/
       ForceCommand internal-sftp
       AllowTcpForwarding no
       GatewayPorts no
       X11Forwarding no



Match user baz
       ChrootDirectory /NAS/baz.com/
       ForceCommand internal-sftp
       AllowTcpForwarding no
       GatewayPorts no
       X11Forwarding no

我怎麼能這樣做。我曾考慮過使用sed,但這似乎只適合一種襯墊?

sed -i 's/foo//g' file.php

而且我不能為每一行都這樣做,因為段落中的大多數行都不是唯一的!有任何想法嗎?

其實,sed也可以取範圍。此命令將刪除Match user foo與第一個空行(包括)之間的所有行:

$ sed '/Match user foo/,/^\s*$/{d}' file


Match user bar
       ChrootDirectory /NAS/bar.co.uk/
       ForceCommand internal-sftp
       AllowTcpForwarding no
       GatewayPorts no
       X11Forwarding no



Match user baz
       ChrootDirectory /NAS/baz.com/
       ForceCommand internal-sftp
       AllowTcpForwarding no
       GatewayPorts no
       X11Forwarding no

然而,就我個人而言,我會使用 perl 的段落模式-00

$ perl -00ne 'print unless /Match user foo/' file
Match user bar
       ChrootDirectory /NAS/bar.co.uk/
       ForceCommand internal-sftp
       AllowTcpForwarding no
       GatewayPorts no
       X11Forwarding no

Match user baz
       ChrootDirectory /NAS/baz.com/
       ForceCommand internal-sftp
       AllowTcpForwarding no
       GatewayPorts no
       X11Forwarding no

在這兩種情況下,您都可以使用-i原地編輯文件(這些將創建名為 的原始文件的備份file.bak):

sed -i.bak '/Match user foo/,/^\s*$/{d}' file

或者

perl -i.bak -00ne 'print unless /Match user foo/' file 

引用自:https://unix.stackexchange.com/questions/192465