Question: I have a directory with more than 500 files, here's a sample of the files:

> 
> random-code\_aa.log 
> 
> 
> random-code\_aa\_r-13.log
> 
> 
> random-code\_ab.log
> 
> 
> random-code\_ae.log
> 
> 
> random-code\_ag.log
> 
> 
> random-code\_ag\_r-397.log
> 
> 
> random-code\_ah.log
> 
> 
> random-code\_ac.log
> 
> 
> random-code\_ac\_r-41.log
> 
> 
> random-code\_ax.log
> 
> 
> random-code\_ax\_r-273.log
> 
> 
> random-code\_az.log
> 
> 
> 

what I would like to do, preferably using a bash loop, is look into the directory for the `*_r-*.log` files and if found then try to see if similar `.log` files exist but without whatever is preceding `_r-*.log`, if found then rename the .log files into their corresponding `_r-*.log` files but change the `r` into `i`.

Better demonstrate with an example from the files sample above:

```
if "random-code_aa_r-13.log" and "random-code_aa.log" exist then 
rename "random-code_aa.log" to "random-code_aa_i-13.log"

```

I've tried with `mv` and `rename` but nothing worked.

Answer: 
This simple BASH script should take care of that:

```
for f in *_r-*.log; do
   rf="${f/_r-*log/.log}"
   [[ -f "$rf" ]] && mv "$rf" "${f/_r-/_i-}"
done

```
You should be able to do that with a parameter substitution:

```
for f in *_r-*.log
do
    stem="${f%_r-*.log}
    num="${f%.log}"; num="${num##_r-}"
    if test -e "${stem}_aa.log"
        then mv "${stem}_aa.log" "${stem}_aa-${num}.log"
    fi
done

```