4

if I have a string like some/unknown/amount/of/sub/folder/file.txt how can I get only the the file.txt sub string, remove the front part, while the length is unknown.

thank you

EDIT: file name could be any length, and sub folders could be any levels.

1
  • uh...I'm not sure, GNU bash?? is that what you are asking? o.O!! Commented Jul 30, 2009 at 19:51

4 Answers 4

13
$ basename "some/unknown/amount/of/sub/folder/file.txt"
file.txt

To generically extract a substring, you can use this syntax

$ hello="abcdef"
$ echo ${hello:1:3}
bcd
Sign up to request clarification or add additional context in comments.

Comments

5

While I agree that the correct answer is to invoke basename, in bash you can also use ## to delete the longest occurrence of a string from the start of a variable.

bash-3.2$ t=/this/is/a/path
bash-3.2$ echo ${t##*/}
path

Comments

4

Use basename command:

orig_path="some/unknown/amount/of/sub/folder/file.txt"
last_comp=$(basename $orig_path)
echo $last_comp

Comments

4

basename some/unknown/amount/of/sub/folder/file.txt

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.