0

I have a file that contains lines like this

proto udp
.
.
.
..
server 10.10.8.0/24 255.255.255.0

I need a way to remove only /24 from this line server 10.10.8.0/24 255.255.255.0 to become

server 10.10.8.0 255.255.255.0

considering that this line is variable but the only constant thing is the / it may be like this

server 198.196.178.0/8 255.0.0.0

so I need a way to remove only /8 from this line to become like this

server 198.196.178.0 255.0.0.0
1
  • 2
    sed '/^server/s|/[0-9]*||' may be enough for your need. Mar 16, 2016 at 9:56

1 Answer 1

0

Using GNU sed with captured groups:

sed -r 's_^(server\s+([^.]+.){3}[0-9]{1,3})/[0-9]+(.*)_\1\3_' file.txt

To edit the file in place, use -i option:

sed -ri 's_^(server\s+([^.]+.){3}[0-9]{1,3})/[0-9]+(.*)_\1\3_' file.txt

Example:

% sed -r 's_^(server\s+([^.]+.){3}[0-9]{1,3})/[0-9]+(.*)_\1\3_' <<<'server 10.10.8.0/24 255.255.255.0'
server 10.10.8.0 255.255.255.0

% sed -r 's_^(server\s+([^.]+.){3}[0-9]{1,3})/[0-9]+(.*)_\1\3_' <<<'server 198.196.178.0/8 255.0.0.0' 
server 198.196.178.0 255.0.0.0
6
  • thats work but it gives me the output to bash ...i need it to replace it in the file Mar 16, 2016 at 9:52
  • @KhalidAboElMaGd No problem, just use -i option..check my edits..
    – heemayl
    Mar 16, 2016 at 9:54
  • @heemayl, when proposing sed -i you should keep in mind two things: (1) For beginners, stress that they test the command without the -i switch or they may cause damage hard to reverse. (2) BSD sed has a -i switch but requires a backup extension, even if it's an empty string (i.e. ''). When this is omitted the command is interpreted as the backup extension, and the filename following it is parsed as a sed command (usually leading to errors). To avoid nasty surprises and for better portability with -i, always include a backup extension even if only ''.
    – Wildcard
    Mar 16, 2016 at 10:01
  • @Wildcard fair points..OP has already tested without the -i, thats why i have suggested it after..check comment..
    – heemayl
    Mar 16, 2016 at 10:03
  • 1
    @Wildcard, with GNU sed, the backup extension has to be stuck to -i which means you can't use -i ''. -i.bak is portable between GNU and BSDs, but neither -i (same as -i'') nor -i '' are. Mar 16, 2016 at 10:35

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .