Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract filename from path using sed or awk

Tags:

linux

unix

sed

awk

I am trying to parse a filename from a modified apache web access log entry that is tab delimited:

/common/common/img/pictos/klArrowRight.gif    /common/common/img/pictos/klArrowRight.gif   03/Dec/2012:00:00:00    127.0.0.1   03/Dec/2012:00:00:00    us   404

I would like it to come out like this:

klArrowRight.gif    /common/common/img/pictos/klArrowRight.gif   03/Dec/2012:00:00:00    127.0.0.1   03/Dec/2012:00:00:00    us   404

I have tried something like this in sed:

's:.*/::'

However, it is too greedy, and it eats the rest of my line. I have been looking through posts, but so far no luck. Any hints?

like image 839
Mark McWhirter Avatar asked Dec 03 '22 01:12

Mark McWhirter


2 Answers

None of the given answers seem to be correct completely when only the extraction of a filename from a given absolute path is desired. Therefore I give here the solution. Let's consider in variable filename we have the complete path, e.g., filename=/ABC/DEF/GHI Then,

echo $filename | awk 'BEGIN{FS="/"}{print $NF}'

will result in the filename GHI.

like image 118
user12531 Avatar answered Dec 16 '22 00:12

user12531


You can do this pretty easily with just sed, as long as you tell it not to be too greedy:

% echo '/img/pictos/klArrowRight.gif 03/Dec/2012' | sed 's,^[^ ]*/,,'
klArrowRight.gif 03/Dec/2012
%

(that is, "starting at the beginning of the line, find the longest-possible list of non-space characters, followed by a slash")

like image 38
Norman Gray Avatar answered Dec 15 '22 23:12

Norman Gray