I have a directory in which I have files with the same suffix:
$ ls ./*.gbk
k141_1208254.region001.gbk
k141_1374899.region001.gbk
k141_1398938.region001.gbk
k141_1444319.region001.gbk
k141_46645.region001.gbk
I want to differentiate these files in another way, changing .region00# according to left to right orientation.
This is the desired output:
k141_1208254.region001.gbk
k141_1374899.region002.gbk
k141_1398938.region003.gbk
k141_1444319.region004.gbk
k141_46645.region005.gbk
There are several folder that have *.gbk
files. How can I do this?
CodePudding user response:
One way to do this would look like:
#!/usr/bin/env bash
counter=1
for f in *.region001.gbk; do # iterate over filenames ending in .region001.gbk
[[ -e $f || -L $f ]] || { # if we have a file that doesn't exist:
echo "ERROR: $f not found" >&2 # ...write an error message to stderr...
exit 1 # ...and exit the script early.
fi
prefix=${f%.region001.gbk} # strip the suffix off the name to get the prefix
printf -v suffix 'regiond.gbk' # calculate a new suffix
newName="${prefix}.${suffix}" # append that to the prefix to get the new name
if [[ $f != $newName ]]; then # if that new name differs from the old name...
mv -- "$f" "$newName" # ...then rename the file.
fi
(( counter )) # finally, increment the counter.
done
Note that not overwriting existing output files (if any .region002
etc. files exist in the directory already) is left as an exercise to the reader.
CodePudding user response:
@Charles Duffy's answer looks good and informative but I made the same thing with my poor bash knowledge.
Below code;
- generate suffixes and save them to an array (001, 002, etc.)
- make a loop for all .gbk files
- parse necessary prefixes with regex from filename (like k141_1208259.region)
- merge prefixes (k141_1208259.region) with suffixes (002) -> (like k141_1208259.region002)
- rename the file by moving it
pad=1000; # 3 digit fixed
declare -a suffixes
file_count=$(ls -l *gbk | wc -l)
for i in $(seq $file_count);
do ((j=pad i))
count=${j#?}
suffixes =($count)
done
iteration=0
for i in ./*.gbk ; do
if [[ "$i" =~ ^.\/(([-_a-zA-Z0-9.]*.)region)[0-9]*(.gbk)$ ]];
then
mv "$i" "${BASH_REMATCH[1]}${suffixes[iteration]}.gbk" ;
((iteration ))
fi
done
This code maybe gives you an idea.