Create New File But Add Number If Filename Already Exists in Bash

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

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

Create file but if name exists add number

In a way, Python has this functionality built into the tempfile module. Unfortunately, you have to tap into a private global variable, tempfile._name_sequence. This means that officially, tempfile makes no guarantee that in future versions _name_sequence even exists -- it is an implementation detail.
But if you are okay with using it anyway, this shows how you can create uniquely named files of the form file#.pdf in a specified directory such as /tmp:

import tempfile
import itertools as IT
import os

def uniquify(path, sep = ''):
def name_sequence():
count = IT.count()
yield ''
while True:
yield '{s}{n:d}'.format(s = sep, n = next(count))
orig = tempfile._name_sequence
with tempfile._once_lock:
tempfile._name_sequence = name_sequence()
path = os.path.normpath(path)
dirname, basename = os.path.split(path)
filename, ext = os.path.splitext(basename)
fd, filename = tempfile.mkstemp(dir = dirname, prefix = filename, suffix = ext)
tempfile._name_sequence = orig
return filename

print(uniquify('/tmp/file.pdf'))

How to create a new file with additional incrementing number when file already exists?

Working Code:

String fileName = "test.txt";

String extension = "";
String name = "";

int idxOfDot = fileName.lastIndexOf('.'); //Get the last index of . to separate extension
extension = fileName.substring(idxOfDot + 1);
name = fileName.substring(0, idxOfDot);

Path path = Paths.get(fileName);
int counter = 1;
File f = null;
while(Files.exists(path)){
fileName = name+"("+counter+")."+extension;
path = Paths.get(fileName);
counter++;
}
f = new File(fileName);

Explanation:

  1. Firstly separate extension and file name without extension and set counter=1 then check if this file exists or not. If exists go to step 2 otherwise got to step 3.

  2. If file exists then generate new name with file name without extension+(+counter+)+extension and check this file exists or not. If exists then repeat this step with increment counter.

  3. Here create file with latest generated file name.

How to increment the filename if file already exists in javascript

You can check this.state.Files before. A recursive function could be used here. Imagine you load a file named export.csv. The second one would export.csv transformed in export_1.csv. But on a third one named export.csv, the verification would be done on export, leading to export_1 => Error !
The best is to do :

const checkNameOfTheFile = (newFileName) => {
// Ex 'export.csv'
const counter = this.state.Files.filter(f => f.fileName === newFileName).length;
// If counter >= 2, an error has already been passed to the files because it means
// 2 files have the same name
if (counter >= 2) {
throw 'Error duplicate name already present';
}
if (counter === 0) {
return newFileName
}
if (counter === 1) {
const newName = `${newFileName.split('.')[0]}_${counter}.${newFileName.split('.')[1]}`;
// Return export_1.csv;
return checkNameOfTheFile(newName);
// We need to check if export_1.csv has not been already taken.
// If so, the new name would be export_1_1.csv, not really pretty but it can be changed easily in this function
}
};

const CompleteData= {
fileData: reader.result,
fileName: checkNameOfTheFile(file.name),
};

Append to file only if it exists

Assuming the file is either nonexistent or both readable and writable, you can try to open it for reading first to determine whether it exists or not, e.g.:

command 3<file 3<&- >>file

3<&- may be omitted in most cases as it's unexpected for a program to start reading from file descriptor 3 without redirecting it first.

Proof of concept:

$ echo hello 3<file 3<&- >>file
bash: file: No such file or directory
$ ls file
ls: cannot access 'file': No such file or directory
$ touch file
$ echo hello 3<file 3<&- >>file
$ cat file
hello
$

This works because redirections are processed from left to right, and a redirection error causes the execution of a command to halt. So if file doesn't exist (or is not readable), 3<file fails, the shell prints an error message and stops processing this command. Otherwise, 3<&- closes the descriptor (3) associated with file in previous step, >>file reopens file for appending and redirects standard output to it.

How to Increment filename if file exists

This problem is always initializative num = 0 so if file exists, it save file0.jpg and not check whether file0.jpg is exists ?
So, To code work. You should check until available :

int num = 0;
String save = at.getText().toString() + ".jpg";
File file = new File(myDir, save);
while(file.exists()) {
save = at.getText().toString() + (num++) +".jpg";
file = new File(myDir, save);
}

write a file, append if it exists otherwise create in bash

   #! /bin/bash
VAR="something to put in a file"
OUT=$1
if [ ! -f "$OUT" ]; then
mkdir -p "`dirname \"$OUT\"`" 2>/dev/null
fi
echo $VAR >> $OUT

# the important step here is to make sure that the folder for the file exists
# and create it if it does not. It will remain silent if the folder exists.

$ sh out hello/how/are/you/file.out
geee: ~/src/bash/moo
$ sh out hello/how/are/you/file.out
geee: ~/src/bash/moo
$ sh out another/file/lol.hmz
geee: ~/src/bash/moo
$ find .
.
./out
./another
./another/file
./another/file/lol.hmz
./hello
./hello/how
./hello/how/are
./hello/how/are/you
./hello/how/are/you/file.out
geee: ~/src/bash/moo
$ cat ./hello/how/are/you/file.out
something to put in a file
something to put in a file
geee: ~/src/bash/moo
$ cat ./another/file/lol.hmz
something to put in a file

the escaped " for dirname are needed if the folder of file has spaces in the name.

Take a file name as input and check if it exists

First of all, I want to thank anyone and everyone who tried to help. After 3 hard working days, I found the answer, here it is:

#!/bin/bash

file="$@"
if [ -f $file ]
then
echo "File exists"
else
echo "File does not exist"
fi

Using this table:



















































Variable NameDescription
$0The name of the Bash script
$1 - $9The first 9 arguments to the Bash script
$#Number of arguments passed to the Bash script
$@All arguments passed to the Bash script
$?The exit status of the most recently run process
$$The process ID of the current script
$USERThe username of the user running the script
$HOSTNAMEThe hostname of the machine
$RANDOMA random number
$LINENOThe current line number in the script

How to check if a file exists in a shell script

You're missing a required space between the bracket and -e:

#!/bin/bash
if [ -e x.txt ]
then
echo "ok"
else
echo "nok"
fi


Related Topics



Leave a reply



Submit