Borealis Borealis - 6 months ago 10
Linux Question

How to extract file name from piped results?

I have a text file with files following this format:

item1 a/b/c/d/file1.csv
item2 a/b/c/d/file2.csv
item3 a/b/c/d/file3.csv
and so on...


To isolate the second item in each row, I use the following:

cat mn_s3_files.txt | awk '{ print $1 }'


Which yields:

a/b/c/d/file1.csv
a/b/c/d/file2.csv
a/b/c/d/file3.csv
and so on...


Now, how can I extract only the basename from the piped results?

For example:

cat mn_s3_files.txt | awk '{ print $1 }' | <some basename command here>


desired output:

file1
file2
file3
and so on...

Answer

Use basename :)

cat mn_s3_files.txt  | awk '{print $2}' | xargs basename

If you get an extra operand error try this:

cat foo | awk '{print $2}' | perl -ne '$_ =~ s[.*/(.*)][$1]; print "$_";'

The perl version is very brute force ie strip everything up to the last / on the line. You might be able to remove awk in that case.

Comments