Bash: remove numbers at the end of names.

前端 未结 3 582
温柔的废话
温柔的废话 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:22

    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

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-01-07 10:32

    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
    
    0 讨论(0)
提交回复
热议问题