Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 exists.

Example:

$ create somefile Created "somefile.ext" $ create somefile Created "somefile-2.ext" 
like image 454
heltonbiker Avatar asked Aug 29 '12 23:08

heltonbiker


People also ask

What does touch do if file already exists?

Traditionally, the main purpose of touch is to change the timestamp of a file, not creating a file. touch creates a file, only when the file(s) mentioned in the argument doesn't exist, otherwise it changes the modification time of the file to current timestamp.

How do you add numbers to a file in Linux?

Method 1 - Using 'nl' command The "nl" command is dedicated for adding line numbers to a file. It writes the given file to standard output, with line numbers added.

How do you add text to a file with multiple names in Linux?

you can simply: echo "my text" | tee -a file1. txt file2. txt . No need to pipe to a second tee.

How do you create a new file in bash?

To create a new file, run the "cat" command and then use the redirection operator ">" followed by the name of the file. Now you will be prompted to insert data into this newly created file. Type a line and then press "Ctrl+D" to save the file.


2 Answers

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 
like image 74
choroba Avatar answered Oct 15 '22 09:10

choroba


Easier:

touch file`ls file* | wc -l`.ext 

You'll get:

$ ls file* file0.ext  file1.ext  file2.ext  file3.ext  file4.ext  file5.ext  file6.ext 
like image 20
Hugoren Martinako Avatar answered Oct 15 '22 10:10

Hugoren Martinako