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

 

posted on 2013-01-28 17:17  name2579  阅读(567)  评论(0编辑  收藏  举报

导航