Move files according to number in filename

夙愿已清 提交于 2019-12-25 07:14:58

问题


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


来源:https://stackoverflow.com/questions/37494081/move-files-according-to-number-in-filename

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!