Search code examples
bashshellsh

How to take multiple files in terminal in BASH shell scripting


I am new in sh and I am trying to scan output files and take some rows starts with "enthalpy new" to a new file. In advance I created a file named step.txt in the directory. There is not a certain number of files so I tried to do it like that:

     for (( i=1; i<=$# ; i++))
     do
     grep "enthalpy new" $i >> step.txt
     done

And I wrote this command to the terminal:

     $bash hw1.sh sample2.out sample1.out

Then, I took these errors:

     grep:  1: No such a file or directory
     grep:  2: No such a file or directory

I am expecting to have step.txt file having 28 lines which 12 of them coming from sample1.out and 16 of them coming from sample2.out. Inside of step.txt will look like:

  enthalpy new = 80 Ry
  enthalpy new = 76 Ry
  ....
  ....
  enthalpy new = 90 Ry

Is there anyone to tell my error and to help me fixing the code?


Solution

  • At present $I is referencing the iterations of the loop and so 1,2,3 .... These files cannot be found by grep and hence the error.

    There are two approaches to ocercome this. $@ contains the parameters passed to the script and so you could try:

    grep "enthalpy new" "$@" >> step.txt
    

    Alternatively, if you want to loop through each parameter/file try:

    for fil in "$@"
    do
          grep  "enthalpy new" "$fil" >> step.txt
    done