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?
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?
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
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}'
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}'