Skip to content
Advertisement

Execute program with different parameters and storing results in txt file

I am trying to execute a program (let’s say myApp) in the ubuntu shell. Normally myApp is called like this: myApp /path/to/file1 /path/tofile2 the output is a matrix which will be printed on the standard output.

What i want to do is to execute myApp for all files in a directory and save the output in a txt file. The last part, i hope is easy which i intend to do with myApp /path/to/file1 /path/tofile2 > myOutputfile.txt.

I am really stuck with calling all files automatically. If have tried to do this:

for i in $(ls /tmp/ch0_*000000{0..483..4}.pcd);
    do 
    f1=$i    
    f2=$i+1 # i also tried f2=i+1
    myApp /tmp/$f1 /tmp/$f2 > myOutput.txt
done

so my problem is that i cannot get to the next filename in the list to pass it to myApp. what i am doing so far is adding ‘+1’ to the existing file string. How can i get the next file from the returned ls output? thanks!

Advertisement

Answer

Aside from the link Inian gave — why you shouldn’t parse the output of ls(1) — you cannot get the “next” item in a bash for loop (at least, to my knowledge).

What you can do is remember the last item.

unset last_i
# Fudging the wildcarding a bit as it is unclear
# what your `ls` was supposed to achieve.
# This is assuming at least one matching file exists,
# otherwise you will get one loop with, literally,
# i=/tmp/ch0_*.pcd
for i in /tmp/ch0_*.pcd
do
    if [[ ! -z $last_i ]]
    then
        myApp $last_i $i >> myOutput.txt
    fi
    last_i="$i"
done

Note:

  • Use direct wildcarding instead of $(ls ...).
  • No semicolon after for.
  • No need for $f1, $f2.
  • With > myOutput.txt, your output file will be overwritten for each loop; with >> output will be appended. Adjust as necessary.
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement