linux_security
linux_security

Reputation: 25

Bash increment input file name

I have been trying to write a better bash script to run a specified program repeatedly with different input files. This is the basic brute force version that works, but i want to be able to use a loop to change the argument before ".txt".

    #!/bin/bash

./a.out 256.txt >> output.txt
./a.out 512.txt >> output.txt
./a.out 1024.txt >> output.txt
./a.out 2048.txt >> output.txt
./a.out 4096.txt >> output.txt
./a.out 8192.txt >> output.txt
./a.out 16384.txt >> output.txt
./a.out 32768.txt >> output.txt
./a.out 65536.txt >> output.txt
./a.out 131072.txt >> output.txt
./a.out 262144.txt >> output.txt
./a.out 524288.txt >> output.txt

I attempted to make a for loop and change the argument:

#!/bin/bash
arg=256

for((i=1; i<12; i++))
{
    #need to raise $args to a power of i
    ./a.out $args.txt << output.txt
}

but i get an error on my ./a.out stating that ".txt" does not exist. What is the proper way to raise args to a power of i and use that as the argument to ./a.out?

Upvotes: 0

Views: 438

Answers (2)

Vytenis Bivainis
Vytenis Bivainis

Reputation: 2376

Check this:

seq 12 | xargs -i echo "256 *  2 ^ ({} - 1)" | bc | xargs -i echo ./a.out {}.txt

If it's OK, then drop echo and add >> output.txt

seq 12 | xargs -i echo "256 *  2 ^ ({} - 1)" | bc | xargs -i ./a.out {}.txt >> output.txt

Upvotes: 1

Tom Fenech
Tom Fenech

Reputation: 74685

This is all that you need to do:

for ((i=256; i<=524288; i*=2)); do ./a.out "$i.txt"; done > output.txt

Every time the loop iterates, i is multiplied by 2, which produces the sequence that you want. Rather than redirecting the output of each iteration separately to the file, I have also moved the redirection outside the loop. This way, the file will only contain the contents from the loop.

In your question, $args is empty (I guess that you meant to put $arg), which is why your filename is just .txt. Also, you have used << rather than >>, which I assumed was a typo.

Upvotes: 3

Related Questions