Get sub string in shell script

if I have a line like some/unknown/amount/of/sub/folder/file.txt , how can I get only the substring file.txt , delete the front part, and the length is unknown .

Thank you

EDIT: the file name can be any length, and the subfolders can be any levels.

+4
source share
4 answers

Use the basename command:

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

To generalize a substring, you can use this syntax

 $ hello="abcdef" $ echo ${hello:1:3} bcd 
+13
source

Although I agree that the correct answer is to call basename, in bash you can also use ## to remove the longest occurrence of a string from the beginning of the variable.

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

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

+4
source

All Articles