2

I am using this command below and trying to separate the columns I only want to get the PID to use it in my python script.

I can easily get this line by line but then how to separate into columns in a non hacky way?

I can easily split by space but lets face it that is a terrible idea, any suggestions?

root@python-VirtualBox:/var/python# lsof | grep TCP
lsof: WARNING: can't stat() fuse.gvfsd-fuse file system /run/user/1000/gvfs
      Output information may be incomplete.
COMMAND  PID USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
sshd    3449 root    3u  IPv4  24248      0t0  TCP *:22 (LISTEN)
sshd    3449 root    4u  IPv6  24257      0t0  TCP *:22 (LISTEN)
1

I think awk is good for this because it splits fields for you:

lsof | awk '$8 == "TCP" { print $2 }'

If field 8 is "TCP", then print field 2.

4

The lsof command is quite full-featured, allowing you to specify many different search criteria. In particular, the -i option lets you search by Internet address, including protocol, rendering grep unnecessary. So you could replace

lsof | grep TCP

with

lsof -i TCP

lsof also allows you to specify which fields you are interested in with the -F option and only output those (one on each line). So we can do

lsof -i TCP -F 'p'

to output a list of PIDs for processes which are using TCP.

However, each of these PIDs is prefixed with a "p" (e.g. "p156"), so finally we can use cut to just get the numerical ID. This gives us a final command of

lsof -i TCP -F 'p' | cut -c 2-

Of course @RobertL's answer is also perfectly fine, but I like to challenge myself to not use AWK to solve all my text-processing challenges.

3

in:

lsof -iTCP -Fp

out:

p1135                                
p6326                                                                  
p16841                                                                 
p18130                                                                 
p37908                                                                 
p41768                                                                 
p51944                                                                 
p71882                                                                 
p74759                                                                 
p79636                                                                 
p82203                                
  • 1
    Why vote this down? It's correct, and provides all results, unlike lsof |grep TCP. – tjt263 Jan 22 '16 at 18:07
  • 1
    Probably because the same answer was already given with more details and a command to strip the 'p' prefix just hours before your answered. I gave you an upvote to compensate, because brevity is also a virtue :) – DylanYoung Oct 19 '18 at 14:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.