Rename files using bash/regex?

旧城冷巷雨未停 提交于 2021-02-05 07:33:13

问题


I have files named:

test-12.5.0_567-release.apk

I want them to look like:

test-release.apk

I realized I can do it with bash:

for file in *release.apk; do
  mv "$file" "`basename $file SOMETHING`NEW_FILE_NAME"; done

It needs some regex I guess ? How would it look like ?

Thanks !


回答1:


You can do:

for file in *release.apk; do
  mv "$file" "${file/-*-/-}"
done



回答2:


Alternatively you can use this:

for file in *release.apk; do
    mv "$file" "${file%-*-*}-release.apk"

I'm removing -12.5.0_567-release.apk and then add -release.apk.

However, IMHO anubhava's solution looks better since it is more precisely doing what you want.




回答3:


Another alternative, with an actual regex and capturing groups. It uses the =~ operator and the BASH_REMATCH array (containing the captured sub groups)

for file in *; do
  # check if the filename matches the regex and extract 2 groups
  if [[ $file =~ ([^-]*-).*-([^-]*) ]]; then
    # use the captured groups
    mv "$file" "${BASH_REMATCH[1]}${BASH_REMATCH[2]}";
  fi
done



回答4:


You can use a regex with the rename command:

rename 's/-*-/-/g' *release.apk



来源:https://stackoverflow.com/questions/35625458/rename-files-using-bash-regex

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