使用 sed 文件添加扫描线



>我正在尝试查找测试并插入行

iface eth0:5 inet static
        address 1.1.1.1
        netmask 255.255.255.0
iface eth0:6 inet static
        address 2.2.2.2
        netmask 255.255.255.0

取代

auto eth0:5
iface eth0:5 inet static
        address 1.1.1.1
        netmask 255.255.255.0
auto eth0:6
iface eth0:6 inet static
        address 2.2.2.2
        netmask 255.255.255.0
sed应该

可以工作,但这个简单的awk也可以做到:

awk '/iface/ {print "auto",$2}1' file
auto eth0:5
iface eth0:5 inet static
        address 1.1.1.1
        netmask 255.255.255.0
auto eth0:6
iface eth0:6 inet static
        address 2.2.2.2
        netmask 255.255.255.0

你来了:

sed -e 's/iface ([^ ]*) .*/auto 1'$'n''&/' file

([^ ]*)将捕获接口的名称,以便我们可以在替换中使用1,因此我们可以插入 auto 1 ,后跟换行符,后跟&表示原始行。

如果要以内联方式替换,可以使用 -i 标志,例如:

sed -ie 's/iface ([^ ]*) .*/auto 1'$'n''&/' /etc/network/interfaces

如果你对 perl 没问题:

perl -i -lane 'if(/^iface/){print "auto $F[1]n$_"}else{print}' your_file

请记住,这是就地替换。如果您不希望就地更换,那么,

perl -lane 'if(/^iface/){print "auto $F[1]n$_"}else{print}' your_file

您也可以使用 awk:

awk '/^iface/{print "auto "$2}1' your_file

最新更新