Bash: remove numbers at the end of names.

℡╲_俬逩灬. 提交于 2019-12-19 04:55:18

问题


I have files like: alien-skull-2224154.jpg snow-birds-red-arrows-thunderbirds-blue-angels-43264.jpg dead-space-album-1053.jpg

How can I remove in bash the "ID" string before .jpg The id is always separated by the before word with "-" Thanks.


回答1:


Here's one way using bash parameter substitution:

for i in *.jpg; do mv "$i" "${i%-*}.jpg"; done

Or for the more general case (i.e. if you have other file extensions), try:

for i in *.*; do mv "$i" "${i%-*}.${i##*.}"; done

Results:

alien-skull.jpg
dead-space-album.jpg
snow-birds-red-arrows-thunderbirds-blue-angels.jpg

As per the comments below, try this bash script:

declare -A array

for i in *.*; do

    j="${i%-*}.${i##*.}"

    # k="$j"
    # k="${i%-*}-0.${i##*.}"

    for x in "${!array[@]}"; do

        if [[ "$j" == "$x" ]]; then
            k="${i%-*}-${array[$j]}.${i##*.}"
        fi
    done

    (( array["$j"]++ ))

    mv "$i" "$k"
done

Note that you will need to uncomment a value for k depending on how you would like to format the filenames. If you uncomment the first line, only the duplicate basenames will be incremented:

dead-space-album.jpg
dead-space-album-1.jpg
dead-space-album-2.jpg
dead-space-album-3.jpg

If you uncomment the second line, you'll get the following:

alien-skull-0.jpg
alien-skull-1.jpg
alien-skull-2.jpg
alien-skull-3.jpg



回答2:


Assuming all file ID's are numbers you could use the rename command.

rename 's/-\d+//' *.jpg

This may not be available to every *nix, so here is a helpful link for alternatives: http://www.cyberciti.biz/tips/renaming-multiple-files-at-a-shell-prompt.html




回答3:


This is the final code that works great. Thank you all for your time!

for i in *.jpg; 
do

if [[  -e "${i%-*}.jpg" ]]; then
    num=1
    while [[ -e "${i%-*}-$num.jpg" ]]; do
        (( num++ ))
    done
 mv "$i" "${i%-*}-$num.jpg";

else 
rename 's/-\d+//' *.jpg
fi
 done


来源:https://stackoverflow.com/questions/14928238/bash-remove-numbers-at-the-end-of-names

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