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"
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.
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.
you can simply: echo "my text" | tee -a file1. txt file2. txt . No need to pipe to a second tee.
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With