Bash: remove numbers at the end of names.

前端 未结 3 586
温柔的废话
温柔的废话 2021-01-07 09:35

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\" s

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-07 10:31

    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
    

提交回复
热议问题