开发者

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 extrac开发者_运维百科t 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


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


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)


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)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜