Get the file name and extension in Shell

 

file="class.cpp"
name=${file%.*}
ext=${file#*.}
echo "name=$name, ext=$ext"

Output:

name=class, ext=cpp

 

if file="/proj/class.cpp", name will be "/proj/class".

 


 

% - means to delete the matched pattern from right to left, it is non-greedy, %% is greedy;

# - means to delete the matched pattern from left to right, it is non-greedy, ## id greedy.

 

e.g., 

file="class.ver2.cpp"
lname=${file%.*}
sname=${file%%.*}
lext=${file#*.}
sext=${file##*.}
echo "lname=$lname, sname=$sname"
echo "lext=$lext, sext=$sext"

will get

lname=class.ver2, sname=class
lext=ver2.cpp, sext=cpp

 

你可能感兴趣的:(shell)