0

How can i write the script using awk to convert a string of IPs like this into comma seperated. I have around 70K IPs.

Current format - '114.124.35.252' '114.79.61.186' '39.225.242.17' '202.62.16.29'

Desired format - '114.124.35.252','114.79.61.186','39.225.242.17','202.62.16.29'
HaveNoDisplayName
  • 8,291
  • 106
  • 37
  • 47
Steve
  • 3
  • 1
  • See [this][1] post. Sounds about the same. [1]: http://stackoverflow.com/questions/6520816/replacing-the-char-using-awk – Sami Apr 06 '15 at 09:42

3 Answers3

0

You can just replace the space with , using sed if there are no other contents with space in the file. Else, edit your question with more details.

sed 's/ /,/g' File

If it is not file content, use this:

sed 's/ /,/g' <<< $string     #string is the variable with the IP string

EDIT:

AMD$ cat File
'114.124.35.252'
'114.79.61.186'
'39.225.242.17'
'202.62.16.29'

1.You can use tr (this will replace the last newline with , as well. See man tr for details)

AMD$ tr '\n', ',' < File
'114.124.35.252','114.79.61.186','39.225.242.17','202.62.16.29',

2.Else, you can use this awk command:

AMD$ awk -v n=$(wc -l < File) '{if(NR!=n){ORS=","}else{ORS="\n"}}1' File
'114.124.35.252','114.79.61.186','39.225.242.17','202.62.16.29'

The default record seperator for awk is '\n'. Change this to , for all but the last line.

Arjun Mathew Dan
  • 5,240
  • 1
  • 16
  • 27
  • Thanks All for your answers. – Steve Apr 07 '15 at 01:21
  • Thanks All for your answers. The list of IPs in the text file is not formatted with a space (Stackoverflow reconstructed it to rows when i listed in the original format). The original list is all listed with a line break like this
    '114.124.35.252'
    '114.79.61.186'
    '39.225.242.17'
    '202.62.16.29'
    – Steve Apr 07 '15 at 01:30
  • Sharing a link on how the original list looks like - https://www.dropbox.com/s/u0q8b1wtw65e7qy/ip.txt?dl=0 – Steve Apr 07 '15 at 01:52
0

Try:

$ awk -F- '{gsub("\047 ","\047,",$2)}1' OFS="-" file
Current format - '114.124.35.252','114.79.61.186','39.225.242.17','202.62.16.29'
cuonglm
  • 2,766
  • 1
  • 22
  • 33
0

Idiomatic awk:

$ awk -v OFS=, '{$1=$1}1' ip.txt
'114.124.35.252','114.79.61.186','39.225.242.17','202.62.16.29'

$1=$1

Reconstitutes the input line replacing the default white-space separator with the new output file separator defined by -v OFS=,

1

Is a "true" pattern, triggering the default action, which is to print the (now reconstituted) line.

jas
  • 10,715
  • 2
  • 30
  • 41