Search code examples
sedmv

Using sed and mv to add characters to files


First off, I'd like to say that I know this is almost an exact duplicate of some posts that I've read, but have not had any luck with referencing.

I have 100+ files that all follow a very strict naming convention of 5_##_<name>.ext My issue was that when originally making these files I failed to realise that 5_100_ and above would mess up my ordering.

I am now trying to append a 0 in front of every number between 01 and 99. I've written a bash script using sed that works for the file contents (the file name is in the file as well):

#!/bin/bash
for fl in *.tcl; do

    echo Filename: $fl

    #sed -i 's/5_\(..\)_/5_0\1_/g' $fl

done

However, this only changes the contents and not the filename itself. I've read that mv is the solution (rename is simpler but I do not have it on my system). My current incarnation of my multiple attempts is:

mv "$fl" $(echo "$file" | sed -e 's/5_\(..\)_/5_0\1_/g') but it gives me an error: mv: missing destination file operand after <filename>

Again, I'm sorry about the duplicate but I wasn't able to solve my issue by reading it. I'm sure I'm just using the combination of mv and sed incorrectly.


Solution was entered in the comments. I was using $file instead of $fl.


Solution

  • Something like this might be useful:

    for n in $(seq 99)
    do
      prefix2="5_$(printf "%02d" ${n})_"
      prefix3="5_$(printf "%03d" ${n})_"
    
      for f in ${prefix2}*.tcl
      do
        suffix="${f#${prefix2}}"
    
        [[ -r "${prefix3}${suffix}" ]] || mv "${prefix2}${suffix}" "${prefix3}${suffix}"
    
      done
    done
    

    Rather than processing every single file, it only looks at the ones that currently have a "5_XX_" prefix, and only renames them if the corresponding "5_XXX_" file doesn't already exist...