I have file.txt containing:
registered
{
hostname-1
{
AAA 32;
BBB uuid-1;
ip 192.168.1.1;
host hostname-1;
...
...
...
}
}
registered
{
hostname-2
{
AAA 31;
BBB uuid-2;
ip 192.168.1.2;
host hostname-2;
...
...
...
}
}
registered
{
hostname-3
{
AAA 33;
BBB uuid-3;
ip 192.168.1.3;
host hostname-3;
...
...
...
}
}
I want to delete one complete registered block based on matching ip.
Eg if ip is 192.168.1.2 then the output should be:
registered
{
hostname-1
{
AAA 32;
BBB uuid-1;
ip 192.168.1.1;
host hostname-1;
...
...
...
}
}
registered
{
hostname-3
{
AAA 33;
BBB uuid-3;
ip 192.168.1.3;
host hostname-3;
...
...
...
}
}
I tried 2 ways to achieve this but could not make it work
1) Using grep: this did not work.
grep -v -B6 -A6 $IP file.txt > out.txt
mv -f out.txt file.txt
2) Using awk: If I give the exact IP in the awk command below then it works
awk '/192.168.1.2/{for(x=NR-6;x<=NR+6;x++)d[x];}{a[NR]=$0}END{for(i=1;i<=NR;i++)if(!(i in d))print a[i]}' file.txt
But I want to pass the variable $IP in the awk command. It is not working
awk -v pattern="${IP}" '$0 ~ pattern/{for(x=NR-6;x<=NR+6;x++)d[x];}{a[NR]=$0}END{for(i=1;i<=NR;i++)if(!(i in d))print a[i]}' file.txt
Any help to find out the problem here would be greatly appreciated.
Thanks.
This might work for you (GNU sed):
sed -n '/^registered/h;//!H;/^}/!b;g;/192\.168\.1\.2/!p' file
Providing the file is as is. This will gather up entire registered blocks and delete the one(s) which contain the string 192.168.1.2
.
IP=192.168.1.2
awk '/'$IP'/{for(x=NR-6;x<=NR+6;x++)d[x];}{a[NR]=$0}END{for(i=1;i<=NR;i++)if(!(i in d))print a[i]}' file.txt
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.