How do you parse a filename in bash?

Nick Pierpoint picture Nick Pierpoint · Sep 8, 2008 · Viewed 38.1k times · Source

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.

Answer

Bobby Jack picture Bobby Jack · Sep 8, 2008

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