Bash: remove numbers at the end of names.

2019-02-15 20:26发布

问题:

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