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 can use sed:

```
for file in *_r-*.log ; do
    barename=`echo $file | sed 's/_r-.*/.log/'`
    newname=`echo $file | sed 's/_r-\(.*\)/_i-\1/'`

    if [ -f $barename ] ; then
        mv $barename $newname
    fi
done

```

You can try to improve the regexes, as it is not safe for some file names. But it should work for file names that contain the minus sign only as the separator character.