0

I have multiple files which are starting with error_* and i want to rename all of those with a particular name. I am using the below script to do that but it is not working.

counter=1
for i in `ls error*`
do
  mv $i ABC$counter_$i
  $(( counter++ ))
done

Sample files which I want to rename

error_CO_5010wgs837in.10   
error_CO_coprofo.7

I want to use counter values while renaming each of the file, if i don't use counter it works fine. But i want to know why the above script doesn't work.here is the output which my script is giving:

ABCerror_CO_5010wgs837in.10
ABCerror_CO_coprofo.7

The output which i am expecting is as below:

ABC1_error_CO_5010wgs837in.10
ABC2_error_CO_coprofo.7
fedorqui
  • 275,237
  • 103
  • 548
  • 598
Gaurav Parek
  • 317
  • 6
  • 20

1 Answers1

2

You are using $counter_ and this looks for the variable counter_. To specify that counter is the variable and you also want a _, use ${counter}_.

This should work:

#!/bin/bash

# to avoid error* match exactly error* if does not expand to any result
shopt -s nullglob

counter=1
for i in error*
do
        echo "mv $i ABC${counter}_$i" #now it is echo; change to mv once you tested it works
        counter=$((counter+1))
done

See different ways to increment a variable: How to increment a variable in bash?.

Community
  • 1
  • 1
fedorqui
  • 275,237
  • 103
  • 548
  • 598