How do you parse a filename in bash?


Question

I have a filename in a format like:

system-source-yyyymmdd.dat

I'd like to be able to parse out the different bits of the filename using the "-" as a delimiter.

1
25
6/9/2018 7:29:55 PM

Accepted Answer

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

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

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

29
9/10/2008 5:22:48 PM

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]}  ==> system
echo ${parts[1]}  ==> source
echo ${parts[2]}  ==> yyyymmdd.dat

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


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon