1

I am taking some input from user and checking details about that.

Example:

$HOME/Documents/test/one.txt

I take the above string as an input and want to retrieve one.txt, I need to further proceed with one.txt.

  • You really should just ask your real question. – bahamat Oct 9 '13 at 5:06
  • @bahamat I want to get one.txt from input. – Death Metal Oct 9 '13 at 5:07
5

@Jordanm has already given you the canonical answer that works for any string. If you are dealing specifically with paths, you can also use the programs basename and dirname:

   basename - strip directory and suffix from filenames
   dirname - strip last component from file name

For example:

$ file="$HOME/Documents/test/one.txt"
$ dir=$(dirname "$file");
$ name=$(basename "$file");
$ echo "The file called $name is in the directory $dir"
The file called one.txt is in the directory /home/terdon/Documents/test
5

This is a common task that can be handled by a parameter expansion in any POSIX shell.

path=$HOME/Documents/test/one.txt
file=${path##*/} # file contains one.txt

Another common method is to use the basename program.

file=$(basename "$path")

The only disadvantage is having to spawn an external program. It's main advantage is that it properly handles paths with a trailing /.

  • 2
    To be pedantic, "$(basename "$path")" is wrong in the unlikely event that $path ends with a newline. This is because a) basename adds an extra newline on the end, and b) $(command) strips all trailing newlines. To make it work requires a perverse workaround, something like this: path=$'/tmp/evil\n'; file="$(basename "$path"; printf x)"; strip=$'\nx'; fixed="${file%%$strip}" – Matt Oct 9 '13 at 6:04
1

If you're doing this with filenames, use the basename command:

$ basename $HOME/Documents/test/one.txt
one.txt

Further:

$ FILE=$(basename basename $HOME/Documents/test/one.txt)
$ echo $FILE
one.txt

If you need to split arbitrary strings with arbitrary delimiters it's a little bit of magic. Read the string into an array and set the input field separator to the delimiter.

Here's an example:

$ IFS='/' read -a my_array <<< "$HOME/Documents/test/one.txt"
$ ARRAY_LENGTH=$(( ${#my_array[@]} - 1 ))
$ echo "${my_array[$ARRAY_LENGTH]}"
one.txt

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.