1
       120          ,     3     <IP address>   <port>   
       100          ,     3     xx.xxx.xx.xxx  xxxx      
       220          ,     3     xxx.xx.xxx.xxx  xxxx  
       280                3     xx.xxx.xx.xxx   xx   

Hey guys, I'm working on a shell script and trying to grep/awk/sed some IP addresses. Cleaing up the output is tricky. Notice the bottom line doesn't have a ,. I'm trying to do soemthing like $ awk '{print $4, $5}' to filter out the IP and port columns but that won't work with the bottom line.

Feels like I'm going about this the wrong way. How can I filter out just the IP and port colomuns?

3
  • Are the columns separated by tabs or spaces? Apr 26, 2017 at 22:44
  • Hey! Separated by spaces.
    – captain21
    Apr 26, 2017 at 22:51
  • Hey there, are you still looking for an answer that properly addresses your question?
    – TopHat
    May 5, 2017 at 20:44

3 Answers 3

0

Since the columns are invariant, you could cut -c32- (man cut) the file.

0

As always in Linux there's more than one way to get the job done. I've placed the text you provided into a file.txt. Here are two possible ways based on the information you've given:

1. awk solution: Use awk's NF variable to start from the last field

linux-okrz:~# awk '{print $(NF-1), $(NF)}' file.txt
address> <port>
xx.xxx.xx.xxx xxxx
xxx.xx.xxx.xxx xxxx
xx.xxx.xx.xxx xx

2. sed solution: Use sed to remove the comma before-hand

linux-okrz:~# sed 's|,||g' file.txt | awk '{print $3, $4}'
<IP address>
xx.xxx.xx.xxx xxxx
xxx.xx.xxx.xxx xxxx
xx.xxx.xx.xxx xx

Note that in both examples the first line is slightly off because there is a space between "IP" and "address". Assuming that in the real output it is an actual IP address that shouldn't be a problem. Also, the second example may not work if you have other instances in the output with which there is an important comma that is needed.

Lastly, these commands are based solely on the output and question provided. It could be that further tweaking would be needed depending on what else is in the file and/or what else you are doing in your script.

2
  • I came here to write about $NF, but saw it was already done! :) However, the use of cat in this context is unnecessary, porkmail.org/era/unix/award.html#cat
    – mgor
    Apr 27, 2017 at 5:44
  • Good point @mgor. Old habits die hard I s'pose. Corrected my answer to be more process sensitive. ;) Thanks!
    – TopHat
    Apr 27, 2017 at 16:47
0

Using grep:

grep -Po '(\d+\.){3}\d+\s+\d+'

You must log in to answer this question.

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