0

I'm trying to parse a result from lsof utility in terminal.

lsof -n -i | grep 192.168.0.105:58281 | cut -d" " -f2

Instead of returning the second column separated by spaced, the output is an empty line. What am I missing?

triple fault
  • 13,410
  • 8
  • 32
  • 45
  • Shouldn't there be a space between `-d` and `" "` ? See [here](http://stackoverflow.com/questions/816820/use-space-as-a-delimiter-with-cut-command) for the thing you wanna get. – Klaus Jul 26 '15 at 19:44
  • No, there is no need in a space. – triple fault Jul 26 '15 at 19:46
  • Are you sure the first part (lsof -n -i and the grep) is returning anything? When I run your code (with an adjusted grep) I do get some output. – Jasper Jul 26 '15 at 19:47
  • I think there should be a space as well as between `-f` and `2`. – Klaus Jul 26 '15 at 19:48
  • Yes, I'm sure. Actually if I try -f7 it returns what I want. Something is messed up with the spaces, I just can't understand why. – triple fault Jul 26 '15 at 19:48
  • @KlausPrinoth spaces don't play here any role. Please check before posting here. – triple fault Jul 26 '15 at 19:50
  • Ok sorry, you're right, anyway couldt it be a bug because there are multiple spaces as delimiter in the output of `lsof`? – Klaus Jul 26 '15 at 19:52
  • I'm suspecting that "multiple spaces" are indeed the root of the problem. However I'm not sure how to workaround it in a "robust enough" way. – triple fault Jul 26 '15 at 19:54
  • 1
    I've found something [here](http://stackoverflow.com/a/4483833/4999641) – Klaus Jul 26 '15 at 19:54
  • @KlausPrinoth, exactly what I looked for, thanks! You can write here an answer so I can accept it. – triple fault Jul 26 '15 at 19:55

3 Answers3

3

The flaw in your code is that lsof outputs multiple spaces as delimiter and cut treats all these spaces as different colums.
To achieve what you want you can use tr -s ' ' to delete the redundant spaces. So you could use something like this:

lsof -n -i | grep 192.168.0.105:58281 | tr -s " " | cut -d" " -f2
Klaus
  • 538
  • 8
  • 26
1

cut considers each space as a separate token. So it prints the space between the 1st and 2nd column.

You could do the same using awk:

lsof -n -i | grep 192.168.0.105:58281 | awk '{print $2}'
P.P
  • 117,907
  • 20
  • 175
  • 238
1

The output columns from lsof are delimited by one or more spaces. So you need to “squeeze” (-s or --squeeze-repeats) them in order for cut to be able to pick out columns.

This can be done by simply adding a tr into your pipeline:

lsof -n -i |tr -s ' ' | grep  ...

But awk is probably a better solution than cut/tr with its ability to more intelligently parse fields. Furthermore, you can eliminate the grep (which wasn’t treating . as you mean without \-escaping) with an Awk regex:

lsof -n -i | awk '/192\.168\.0\.105:58281/ {print $2}'
Micah Elliott
  • 9,600
  • 5
  • 51
  • 54