Extracted from StackOverflow: https://stackoverflow.com/questions/428109/extract-substring-in-bash
Generic solution where the number can be anywhere in the filename, using the first of such sequences:
number=$(echo $filename | egrep -o '[[:digit:]]{5}' | head -n1)
Another solution to extract exactly a part of a variable:
number=${filename:offset:length}
If your filename always have the format
stuff_digits_...
you can use awk:number=$(echo $filename | awk -F _ '{ print $2 }')
Yet another solution to remove everything except digits, use
number=$(echo $filename | tr -cd '[[:digit:]]')
I need to loop through the directory and take the filename and crop off the name assuming that the first 6 numbers are the ID number then change it to the final form. I had to ignore all the spacing and junk after the number and just made the assumption that all I needed was the numbers in front of the file.find . -print0 | while read -d $'\0' file; do number=$(echo $file | egrep -o '[[:digit:]]{6}' | head -n1); mv ${number}* ${number}.jpg ; done
I had some problems with files with the hyphen.
ls > /tmp/list
I needed to export a list of file then manipulate with VIM, keeping only the first work in each line then use the file list to iterate through
:1,$s/\(\s*\w\+\).*/\1/g
for x in `cat /tmp/list`; do number=$(echo $x | egrep -o '[[:digit:]]{6}' | head -n1); mv ${number}* ${number}.jpg; done