Search code examples
linuxtext-editorserver-side-scripting

grep only for certain word on line


Need to grep only the word between the 2nd and 3rd to last /

This is shown in the extract below, to note that the location on the filename is not always the same counting from the front. Any ideas would be helpful.

/home/user/Drive-backup/2010 Backup/2010 Account/Jan/usernameneedtogrep/user.dir/4.txt


Solution

  • I'd use awk:

    awk -F/ '{print $(NF-2)}'
    
    • splits on /
    • NF is the index of the last column, $NF the last column itself and $(NF-2) the 3rd-to-last column.

    You might of course first need to filter out lines in your input that are not paths (e.g. using grep and then piping to awk)