Home > OS >  bash: change names of multiple filles
bash: change names of multiple filles

Time:06-28

within the workdir I have number of files

mol0.pdb
mol1.pdb
mol2.pdb
...
mol888.pdb

I need to rename this files changing the number 1 for each file in order that it could became like:

mol1.pdb
mol2.pdb
mol3.pdb
...
mol889.pdb

Could you suggest me some simple solution using bash terminal without possibility to make a script each time and run a loop:

for file in *.pdb
do
  # some command to change the number e.g. using i conter with mv
done

CodePudding user response:

list=( mol*.pdb )
while IFS= read -r n; do
  mv "mol$n.pdb" "mol$((n   1)).pdb"
done < <( printf '%s\n' "${list[@]}" | sed 's/mol\(.*\)\.pdb/\1/' | sort -nr )

sort -rn is here to sort the list of numbers in reverse order such that renaming a file never overwrites another.

CodePudding user response:

here you go:

#!/bin/env bash

for file in *.pdb
do
    mv $file "${file%%[[:digit:]]*}$((${file//[!0-9]/} 1))".pdb;
done

first pattern remove everything with digits and beyond so we have "file123" becomes "file" now get the file name again and remove the words replacing them with nothing, getting the number, and sum 1, and last we add the extension. Just move one filename to another, and we are done.

CodePudding user response:

Another approach; if there are a lot of files this might be a little faster.

EDITED
This line was broken:

$: # lst=(file*.xmp); # this is the original assignment that mis-orders the filenames 

Changing it to this one should work, but gains a bit less less over Renaud's solution, which is probably easier for some to read. YMMV.

$:  mapfile -t lst < <( printf "%s\n" file*.xmp | sort -n -k1.5,1 )
$: ndx=${#lst[@]};
$: while [[ -n "${lst[--ndx]}" ]] && ((ndx>=0)); do echo mv "${lst[ndx]}" "newDir/file$((ndx 1)).xmp"; done
mv file9.xmp newDir/file10.xmp
mv file8.xmp newDir/file9.xmp
mv file7.xmp newDir/file8.xmp
mv file6.xmp newDir/file7.xmp
mv file5.xmp newDir/file6.xmp
mv file4.xmp newDir/file5.xmp
mv file3.xmp newDir/file4.xmp
mv file2.xmp newDir/file3.xmp
mv file1.xmp newDir/file2.xmp
mv file0.xmp newDir/file1.xmp

Falls apart if there are any gaps in your initial numbering, though.

  •  Tags:  
  • bash
  • Related