linux shell script 使用正则表达式替换查找文本

subnet 125.217.241.0 netmask 255.255.255.128{
option domain-name-servers 202.38.193.33,202.112.17.33;
option domain-name "scut.edu.cn";
option routers 125.217.241.126;
option broadcast-address 125.217.241.127;
default-lease-time 600;
max-lease-time 6000;
pool {
allow members of "allocation-class-19664";
range 125.217.241.1 125.217.241.125;
}
}

这是dhcpd.conf文件里的,我要写一个shell script,能够实现替换
subnet
netmask
option domain-name-servers
option domain-name
option routers
option broadcast-address
default-lease-time
max-lease-time
allow members of "allocation-class-19664"
range
这些字段,意思就是,执行这个script的时候,会询问我subnet是?例如我输入192.168.0.0,然后就能把我输入的替换了文件里的125.217.241.0,其他的字段都能实现这样的替换
请大家帮帮忙?

ps:这个dhcpd.conf文件有10000行,我还要准备找到对应的这一行subnet 125.217.241.0 netmask 255.255.255.128,然后再进行替换
这用正则表达式要怎么写呢?请大家再帮下忙
最新回答
峩只是忘不掉回忆

2024-11-26 07:41:21

我也写个例子:
#!/bin/sh
read -p "Pls input subnet: " $subnet
read -p "Pls input netmask: " $netmask
sed -i "s_subnet_subnet $subnet netmask $netmask{_" dhcpd.conf
----------------------------------------------------------------------------------------
更新一下。
read -p "Pls input subnet: " $subnet
read -p "Pls input netmask: " $netmask
sed -i “s/^\(.*subnet \).*\( netmask \).*[0-9]\(.*\)$/\1$subnet\2$netmask\3/” dhcpd.conf

sed中正则匹配时可以在不需要变化的文本两边插入带反斜杠的圆括号来定义区域,然后通过区域号\x(x从1开始)来引用这些由圆括号界定的区域。这样就可以实现只改变部分区域而另一部分保持不变。
忘了我就好

2024-11-26 07:44:00

grep '^[0-9]\$' test.txt | grep '^[1-9]'

如果是变量

echo $var | grep '^[0-9]\$' | grep '^[1-9]'

$表示行尾

这个正则不匹配 12a 这样的字符串

你的变量内容是什么样的?

我用来测试的 test.txt 的内容:
123
321
123212
001
010
100
10000
0011
10101
1101
1
2
3
11
22
33
1a
2a
后巷的猫街少女

2024-11-26 07:35:42

read shu
sed -i "s#max-lease-time.*;#max-lease-time $shu;#g" dhcp.conf

只给你写个例子