Borealis Borealis - 2 years ago 73
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:

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:

and so on...

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download