How to extract specific elements from a filename?

Using parameter expansion

$ touch 2014-11-19.8.ext 2014-11-26.1.ext
$ for f in *.ext; do d="${f:0:4}${f:5:2}${f:8:2}"; echo "$d"; done
20141119
20141126
  • ${f:0:4} means 4 characters starting from index 0 and f is variable name
  • replace echo "$d" with your code

To loop over every file in the current directory and compare their filenames to the desired pattern, then set a variable containing the date pieces

for f in *
do 
  [[ $f =~ ^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])(.*) ]] && 
  yourvar="${BASH_REMATCH[1]}${BASH_REMATCH[2]}${BASH_REMATCH[3]}"
done

This uses bash's [[ ability to use regular expression matching to place the date pieces into the BASH_REMATCH array.


You can do it interactively by using GNU sed:

$ sed 's/^\([0-9]\{4\}\)-\([0-9]\{2\}\)-\([0-9]\{2\}.*\)/\1\2\3/g' stuff.txt

For multiple files (if in same directory and no other considered files in directory):

for file in *
do
    if [ -f "$file" ]
    then
          sed 's/^\([0-9]\{4\}\)-\([0-9]\{2\}\)-\([0-9]\{2\}\).*/\1\2\3/g' "$file"
    fi
done