1

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

1
  • 3
    use a variable and increment it. Something like let i=$i+1 Commented Jun 11, 2014 at 19:28

3 Answers 3

1

I can do this such as following.

i=1
for file in /dir
do
    somecommand $file /newdir/output${i}.txt
    i=$(($i + 1))
done
Sign up to request clarification or add additional context in comments.

Comments

1

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 [[ ]])

2 Comments

The code highlighting appears to catch wrong language(looks like C or something). I'd suggest adding <pre><code class="bash> ... </code></pre> to your answer, or only <code class="bash"> ... </code>.
@quapka Thanks the fix is good enough. (Update: I instead used <!-- language: lang-bash -->)
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.