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

有帮助吗?

解决方案

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)

其他提示

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

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)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top