使用sed文件添加扫描行

使用sed文件添加扫描行,sed,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 n

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

范例

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 -e 's/iface \([^ ]*\) .*/auto \1\'$'\n''&/' file
\([^]*\)
将捕获接口的名称,因此我们可以在替换中使用
\1
,因此我们可以插入as
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

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

这和我写的不一样吗?是的,你是对的,但仅仅相隔几分钟,我在写我的时没有看到你。+1很好,很简单!
sed
的优点是要替换的
-i
标志。您可以模拟
-i
执行此操作
awk'/iface/{print“auto”、$2}1'文件>tmp和mv tmp文件
堆栈溢出欢迎。关于代码的问题应该显示对该问题的最低理解。您能用
sed
发布您的实际尝试吗?