Skip to content
Advertisement

How do I get just the filename from lsof?

I want to use lsof to create a list of open files in a folder. I’m using macOS, but understand this is common to *nix.

In man lsof, it seems the the -Fn option is closest to what I want, but I can’t get further than that. I’m piping to cut to get to just the filename. So this is the command I’m using:

$ lsof -Fn dir1 | cut -c2-

I’m expecting

dir1/file1.txt

I’m getting

32783
34
dir1/file1.txt
32785
3
dir1/.DS_Store

Advertisement

Answer

Could you please try following(since no samples were posted so tested in my test box only).

lsof  | awk 'match($0,//([^ ])*|/([^$])*/){print substr($0,RSTART,RLENGTH)}'


EDIT: Since OP need not to have files with DOT in their names(basically hidden ones I think) then one could try following.

lsof  | 
awk '
FNR>1 && match($0,//.*/){
   val=substr($0,RSTART,RLENGTH)
   if(val !~ //./){
     print val
   }
   val=""
}'
Advertisement