Extract Filename from File Using Shell Script

Extract Filename from File Using Shell Script

I have a text file which has the following line:

/u/tux/abc/spool/frtbla_mcdetc_0000149099_20101126135009990_1.tif

I want to extract frtbla_mcdetc_0000149099_20101126135009990_1.tif; the word after the last slash (/).

1

5 Answers

If you are in a Linux-like environment you can use the basename utility:

basename $(<your_file)
1

use this command

cat text_file_name | cut -d '/' -f 6
2

If you know the exact format of the directory structure and it won't alter, you can use cut:

$ cut -f6 -d '/' file.txt

Here uses cut to treat the directory separators as a delimiter and extract the 6th one.

If instead all you know is it is the last part of a line but don't know the directory structure, you can use rev as well:

$ rev file.txt | cut -f1 -d '/' | rev

Here the file is reversed and the first field is extracted, before being reversed again.

The following applies to all strings in a shell, not just filenames, and is far easier than cut because you don't need to know how many fields there are before the one you want:

$ foo=/path/to/file/split/by/slashes.txt
$ echo ${foo##*/}
slashes.txt

This uses the 'greedy trim', i.e. trim everything until the last '/' as described here:

${foo  <-- from variable foo
  ##   <-- greedy front trim
  *    <-- matches anything
  /    <-- until the last '/'
 }

I don't know what the standard shell is in Aix, but bash is available and supports edited expansion of variables.

If your full name is in the variable FileName, then ${FileName##*/} displays the name with all leading characters deleted as far as the last /; by contrast ${FileName#*/} deletes up to the first /, while ${FileName%/*} deletes trailing characters from the last / (ie the directory path).

If you generate the file name(s) by a find command, then you need a command like:

find ... | while read FileName; do echo ${FileName##*/}; done

If in a text file:

while read FileName; do echo ${FileName##*/}; done < FileList.txt

Replace the echo command by whatever processing you need to do with the name.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

David Miller
Author

David Miller

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.