Create new file but add number if filename already exists in bash

前端 未结 8 1564
Happy的楠姐
Happy的楠姐 2020-12-08 09:56

I found similar questions but not in Linux/Bash

I want my script to create a file with a given name (via user input) but add number at the end if filename already ex

相关标签:
8条回答
  • 2020-12-08 11:02

    The following script can help you. You should not be running several copies of the script at the same time to avoid race condition.

    name=somefile
    if [[ -e $name.ext || -L $name.ext ]] ; then
        i=0
        while [[ -e $name-$i.ext || -L $name-$i.ext ]] ; do
            let i++
        done
        name=$name-$i
    fi
    touch -- "$name".ext
    
    0 讨论(0)
  • 2020-12-08 11:03

    A simple repackaging of choroba's answer as a generalized function:

    autoincr() {
        f="$1"
        ext=""
    
        # Extract the file extension (if any), with preceeding '.'
        [[ "$f" == *.* ]] && ext=".${f##*.}"
    
        if [[ -e "$f" ]] ; then
            i=1
            f="${f%.*}";
    
            while [[ -e "${f}_${i}${ext}" ]]; do
                let i++
            done
    
            f="${f}_${i}${ext}"
        fi
        echo "$f"
    }
    
    touch "$(autoincr "somefile.ext")"
    
    0 讨论(0)
提交回复
热议问题