Sarath R Nair
Sarath R Nair

Reputation: 495

Bash shell scripting to update filenames in loop

I have to create a shell script to execute the following.

for file in /dir
do
    somecommand $file /newdir/outputname.txt
done

My problem is for each loop I have to give new name for "outputname.txt' , like 'output1.txt' in loop1 , 'output2.txt' in loop2 and so on. How to do that ? Any help would be appreciated

Upvotes: 1

Views: 74

Answers (3)

konsolebox
konsolebox

Reputation: 75458

This would not overwrite files that already exists in /newdir.

i=0
for file in /dir/*; do
    until [[ ! -e /newdir/output$((++i)).txt ]]; do
        continue
    done
    somecommand "$file" "/newdir/output${i}.txt"
done

  *  Always place arguments with variables around double-quotes to prevent word splitting. (Specially not necessary in [[ ]])

Upvotes: 1

Pankrates
Pankrates

Reputation: 3094

To put @rpax suggestion into a full answer:

i=0
for file in /dir
do
    i=$(($i+1))
    mv $file "/${newdir}/output_${i}.txt"
done

Upvotes: 0

xiaodongjie
xiaodongjie

Reputation: 246

I can do this such as following.

i=1
for file in /dir
do
    somecommand $file /newdir/output${i}.txt
    i=$(($i + 1))
done

Upvotes: 1

Related Questions