A postdoc A postdoc - 6 months ago 18
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

fooNNN_bar.txt
I would like to organise them like
/NNN/fooNNN_bar.txt


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?

#!/bin/bash
for filename in foo*.txt;
do
echo "${filename}" | grep -Eo '[0-9]{1,4}';
done

Answer

Assuming your grep works as you want:

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