A postdoc A postdoc - 1 year ago 72
Bash Question

Move files according to number in filename

I am trying to move files in folders according to a number in their names.
Files are names like

I would like to organise them like

Here is what I have for now. It prints me the folder each file would have to move to. I'm not sure how to collect the number to add it into a mv command. Is this even the correct way to do it?

for filename in foo*.txt;
echo "${filename}" | grep -Eo '[0-9]{1,4}';

Answer Source

Assuming your grep works as you want:

  for filename in foo*.txt; do 
      num=$(echo "${filename}" | grep -Eo '[0-9]{1,4}')
      mkdir -p "$num"
      mv "$filename" "$num"