P Oliveira
P Oliveira

Reputation: 23

Replace in line using sed

I'm creating a shell script, which reads the following list.log

1.15.2.119
1.15.86.33
1.15.251.60
1.20.178.145/31
1.37.33.24
1.54.202.216
1.58.10.126/28
1.80.225.84
1.116.240.174/30


I would like to add a /32 IP at the end of all IPs except the ones that already exist /32 something.

Example:

1.14.191.227/32
1.15.2.119/32
1.15.86.33/32
1.15.251.60/32
1.20.178.145/31
1.37.33.24/32
1.54.202.216/32
1.58.10.126/28
1.80.225.84/32
1.116.240.174/30


My return is doubling the /32

cat list.log | sed 's/$/\/32/'

1.14.191.227/32
1.15.2.119/32
1.15.86.33/32
1.15.251.60/32
1.20.178.145/31/32
1.37.33.24/32
1.54.202.216/32
1.58.10.126/28/32
1.80.225.84/32
1.116.240.174/30/32

Upvotes: 2

Views: 71

Answers (3)

sseLtaH
sseLtaH

Reputation: 11207

Using sed

$ sed 's|\.[0-9]\+$|&/32|' list.log
1.15.2.119/32
1.15.86.33/32
1.15.251.60/32
1.20.178.145/31
1.37.33.24/32
1.54.202.216/32
1.58.10.126/28
1.80.225.84/32
1.116.240.174/30

Upvotes: 1

RavinderSingh13
RavinderSingh13

Reputation: 133428

This could be easily done in awk, please try following awk program. Written and tested with shown samples.

awk '!/\/32$/{$0=$0"/32"} 1' Input_file

Explanation: Simple explanation would be, checking condition if line doesn't ending with /32 then add /32 to current line and mentioning 1 will print edited/non-edited current line.

Upvotes: 1

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626689

You can add /32 to the end of lines that do not contain /

sed  '\,/,!s,$,/32,' list.log > newlist.log

Details:

  • \,/,! - find lines not containing /
  • s,$,/32, - and replace end of string position with /32 there.

See the online demo:

#!/bin/bash
s='1.15.2.119
1.15.86.33
1.15.251.60
1.20.178.145/31
1.37.33.24
1.54.202.216
1.58.10.126/28
1.80.225.84
1.116.240.174/30'

sed  '\,/,!s,$,/32,' <<< "$s"

Output:

1.15.2.119/32
1.15.86.33/32
1.15.251.60/32
1.20.178.145/31
1.37.33.24/32
1.54.202.216/32
1.58.10.126/28
1.80.225.84/32
1.116.240.174/30

Upvotes: 0

Related Questions