Loading...

File Formatting with sed

Answer #1 100 %

You can use

sed -E 's/^([0-9]+(\.[0-9]+){3})[[:space:]]+([^[:space:]"]+)$/\1 "\3"/' file > newfile

With GNU sed:

sed -i -E 's/^([0-9]+(\.[0-9]+){3})\s+([^[:space:]"]+)$/\1 "\3"/' file

Details:

  • ^ - start of string
  • ([0-9]+(\.[0-9]+){3}) - one or more digits and then 3 occurrences of . and one or more digits
  • [[:space:]]+ - one or more whitespaces
  • ([^[:space:]"]+) - Group 3: one or more chars other than " and whitespace
  • $ - end of string.

See the online demo:

#!/bin/bash
s='10.20.30.40 "User 1"
73.15.16.24 NewUser
124.18.21.17 "User 2"
27.76.58.248 "User 3"
39.16.87.227 "User 4"
211.129.20.52 "User 5"
175.15.118.110 "User 6"'

sed -E 's/^([0-9]+(\.[0-9]+){3})[[:space:]]+([^[:space:]"]+)$/\1 "\3"/' <<< "$s"

Output:

10.20.30.40 "User 1"
73.15.16.24 "NewUser"
124.18.21.17 "User 2"
27.76.58.248 "User 3"
39.16.87.227 "User 4"
211.129.20.52 "User 5"
175.15.118.110 "User 6"
Tags: bashsed

You’ll also like:


© 2022 CodeForDev.com -