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

前端 未结 8 1572
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 10:59

    Use touch or whatever you want instead of echo:

    echo file$((`ls file* | sed -n 's/file\([0-9]*\)/\1/p' | sort -rh | head -n 1`+1))
    

    Parts of expression explained:

    • list files by pattern: ls file*
    • take only number part in each line: sed -n 's/file\([0-9]*\)/\1/p'
    • apply reverse human sort: sort -rh
    • take only first line (i.e. max value): head -n 1
    • combine all in pipe and increment (full expression above)

提交回复
热议问题