Home > Blockchain >  Iterative file name in bash
Iterative file name in bash

Time:11-27

I want to iterate over different file names. The file names are XY1.txt, XY2.txt...XY500.txt. Each file that is taken as input generates 3 output files which I want to rename according to the current index. For XY1.txt, output1.txt becomes 1_1.txt, output2.txt becomes 1_2.txt and so on. But I do not know how to change the filename as per index. I looked it up but I was not finding what I needed on this website or elsewhere. I am new to bash. The below pseudo code is what I was able to write until now. Please help me out

    for i in {1..500} ; 
         filename = "XY" str(i)   ".txt"  ;
         do ./CompiledCodeFile  -filename -use_option 4; 
         mv output1.txt str(i) "_1.txt"   ;
         mv output2.txt str(i) "_2.txt"   ;
         mv output3.txt str(i) "_3.txt"   ;
    done

CodePudding user response:

edit: corrected a little error in the code.

#!/bin/bash

for i in {1..500}
do
    filename="XY$i.txt"
    ./CompiledCodeFile  "$filename" -use_option 4
     mv output1.txt "${i}_1.txt"
     mv output2.txt "${i}_2.txt"
     mv output3.txt "${i}_3.txt"
done

notes:

  • $i and ${i}, what's the difference?

They're the same thing, but sometimes you need to use the ${} for differentiating the variable name from the following letters (here the _)

  • Why use double quotes for expanding variables, for example "$filename"?

edit: correction after @MikaelKjær comment.
Because that's almost mandatory. Not using double quotes is the cause of a lot of errors, while using double quotes can only be wrong for a very few cases (the only ones that I can think of is [[ xyz == $regexp ]] or the likes).

CodePudding user response:

for i in `seq 500`; do
mv output${i}.txt ${i}_${i}.txt
done
  1. use seq function to generate integer from 1 to 500
  2. In bash, the type of variable is string in default.
  •  Tags:  
  • bash
  • Related