How do you parse a filename in bash? How do you parse a filename in bash? shell shell

How do you parse a filename in bash?


You can use the cut command to get at each of the 3 'fields', e.g.:

$ echo "system-source-yyyymmdd.dat" | cut -d'-' -f2source

"-d" specifies the delimiter, "-f" specifies the number of the field you require


A nice and elegant (in my mind :-) using only built-ins is to put it into an array

var='system-source-yyyymmdd.dat'parts=(${var//-/ })

Then, you can find the parts in the array...

echo ${parts[0]}  ==> systemecho ${parts[1]}  ==> sourceecho ${parts[2]}  ==> yyyymmdd.dat

Caveat: this will not work if the filename contains "strange" characters such as space, or, heaven forbids, quotes, backquotes...


Depending on your needs, awk is more flexible than cut. A first teaser:

# echo "system-source-yyyymmdd.dat" \    |awk -F- '{printf "System: %s\nSource: %s\nYear: %s\nMonth: %s\nDay: %s\n",              $1,$2,substr($3,1,4),substr($3,5,2),substr($3,7,2)}'System: systemSource: sourceYear: yyyyMonth: mmDay: dd

Problem is that describing awk as 'more flexible' is certainly like calling the iPhone an enhanced cell phone ;-)