Hi,
This is my first post here.
I am using cygwin on Windows 7.
I am starting with a data file with filename "name_1.ext", like "20180831_snapgenotypes_1.csv".
The "1" before ".ext" is a version number. Integers (0-99) are sufficient. They don't have to be like "1.0.0".
The filename may contain other "" or "-" characters.
The filename might not have a version number, as in "name.ext" or "20180831_snapgenotypes.csv".
I want to leave the current filename and the contents of the file intact. I want to do something (or nothing) to the file contents and save the output to a new file of the same name but increment the version number by 1.
"name.ext" should become "name_1.ext".
"name_1.ext" should become "name_2.ext".
and so on.
I found this post "unix-for-dummies-questions-and-answers/228027-incrementing-new-file-version-number.html" and wrote:
#!/bin/bash
infile=20180831_snapgenotypes_1.csv
echo "infile: "$infile
name=${infile%_*} # Strip off the last "_" and everything after it.
version=${infile##*_} # Strip off the name and "_".
version=${version%.*} # Strip off the .ext to get just the extension.
extension=${infile##*.} # Strip off everything before ext.
outfile="${name}_$((version + 1)).$extension"
echo "outfile: "$outfile
This seems to work if my infile has a version number "_nn".
I tried to add a test whether the filename has this version number and, if not, name the outfile "name_1.ext". My echo statements are just for debugging:
#!/bin/bash
infile=$1
echo "infile: "$infile
name=${infile%.*} # Strip off the extension.
echo '${name} =' "${name}"
extension=${infile##*.} # Strip off everything before ext.
echo '${extension} =' "${extension}"
version_dot=${infile##*_} # Strip off the name and "_".
echo '${version_dot} =' "${version_dot}"
version=${version_dot%.*} # Strip off the extension.
echo '${version} =' "${version}"
if [ ${version} != [[:digit:]]] # This condition is not working.
then ${infile}="${name}_1.${extension}"
else name=${infile%_*} # Strip off the last "_" and extension.
fi
echo '${name} =' "${name}"
outfile="${name}_$((version + 1)).${extension}"
echo "outfile: "$outfile
My test
if [ ${version} != [[:digit:]]] # If the "version number" is not a (1 - 2 digit) number, but text.
is not correct. It always evaluates to false.
There is an error from this line: [: missing `]'. I don't get that clue.
Infile 20180831_snapgenotypes.csv becomes outfile 20180831_1.csv.
Infile 20180831_snapgenotypes_1.csv becomes outfile 20180831_snapgenotypes_2.csv (correct).
I am trying to make this as simple as possible, but a call to sed, AWK, or Perl would be ok.
Thank you!