1

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

Grimlockz
  • 2,541
  • 7
  • 31
  • 38

3 Answers3

1

Here is a Perl script that does the job:

my $str = q!/home/user/Drive-backup/2010 Backup/2010 Account/Jan/usernameneedtogrep/user.dir/4.txt!;
my $res = (split('/',$str))[-3];
print $res;

output:

usernameneedtogrep
Toto
  • 89,455
  • 62
  • 89
  • 125
0

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)

mhyfritz
  • 8,342
  • 2
  • 29
  • 29
  • If I wanted to get the 3rd column as well would that be another AWK command next to it or before it – Grimlockz Jun 16 '11 at 17:03
  • This would print the 3rd and the 3rd-to-last column: `awk -F/ '{print $3, $(NF-2)}'`. Is that what you need? – mhyfritz Jun 16 '11 at 17:09
0

a regular expression something like this should do the trick:

/.\/(.+?)\/.*?\/.*$/

(note I'm using lazy searches (+? and *?) so that it doesn't includes slashes where we don't want it to)

Spudley
  • 166,037
  • 39
  • 233
  • 307