Extracting a date from a file name

Whenever you have a shell script that handles a file with a date (or some other information) and you want to use that, you can do the following:


# obviously, my file is a csv-file, and I'm stripping the extension and the path.
# the file is called somefile-20160308.csv
FILE=`basename /somepath/somefile* .csv`

# the following line extracts the date
DATE=`expr "$FILE" : ".........\(........\)"`

echo $FILE
echo $DATE


Add new comment

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.
Enter the characters shown in the image.