Move files according to number in filename

2019-09-12 03:21发布

问题:

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

回答1:

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