FenderBender
FenderBender

Reputation: 313

awk: Extracting file name from full path

I have a listing for a file like this:

-rw-r--r--   3 knsdkls users  336207616 2014-11-10 07:15 /hive/some/thing/path/location/data/plants/zombies/Filename.txt

From this, I would like to extract the file size and the filename.

I tried awk:

awk '{print $5,$NF}'

Which gives:

336207616  /hive/some/thing/path/location/data/plants/zombies/Filename.txt

I would like:

336207616  Filename.txt

Please guide me. Further, the number of sub-directories in the file path is not constant.

Thanks.

Upvotes: 3

Views: 9545

Answers (3)

Avinash Raj
Avinash Raj

Reputation: 174706

Through awk's split function.

$ awk '{n=split($NF,a,"/");print $5,a[n]}' file
336207616 Filename.txt

Explanation:

  • split($NF,a,"/") splits the last field according to the delimiter / and store the splitted parts into an array a. The total number of splitted parts are stored into an variable called n. So for this case, the variable n contains 10.

  • print $5,a[n] This prints the fifth field plus the last element stored in the array a

Upvotes: 4

nu11p01n73R
nu11p01n73R

Reputation: 26667

You can use gsub function

$ awk '{gsub(/.*\//, "", $NF); print $5,$NF}' input
336207616 Filename.txt
  • gsub(/.*\//, "", $NF) subtitutes anything, .* till the / with null string ""

  • print $5,$NF prints the fifth and last field

Upvotes: 0

Jotne
Jotne

Reputation: 41456

This should do:

awk -F" +|/" '{print $5,$NF}'
336207616 Filename.txt

Just add / as separator.

Upvotes: 3

Related Questions