Im using read in a while loop to automatically change a makefile after download.

Here is part of the script,

    while read a; do
    if [[ "$a" = "FCOMPL=g77" ]]
    then echo "FCOMPL=gfortran" >> makefile
    elif [[ "$a" = "FFLAGC=-Wall -O" ]]
    then echo "FFLAGC=-Wall -O -fno-backslash" >> makefile
    echo $a >> makefile
    done <makefile.orig

The problem is that I lose the tabulation.

Any idea of how I can avoid that?


Instead of using bash to do the task, you could learn sed:

sed -e 's/^FCOMPL=g77$/FCOMPL=gfortran/' \
    -e '/^FFLAGC=-Wall -O$/s/$/ -fno-backslash/' makefile.orig > makefile

Each -e gives sed a command to perform. In this case (1st -e), the s command performs a substitution: s/foo/bar/ replaces the 1st occurrence of foo on each line by bar. To be sure we work on complete line, I added ^ (beginning of the line) and $ (end of the line).

You can prefix a command by a selector. In this case (2nd -e), the s command is applied only to a line matching ^FFLAGC=-Wall -O$.

You could even use the -i flag to replace the file:

sed -i -e 's/^FCOMPL=g77$/FCOMPL=gfortran/' \
       -e '/^FFLAGC=-Wall -O$/s/$/ -fno-backslash/' makefile
| improve this answer | |

Found a solution!! I applied what is taught here http://en.kioskea.net/faq/1757-how-to-read-a-file-line-by-line

    old_IFS=$IFS      # save the field separator           
    IFS=$'\n'     # new field separator, the end of line
    IFS=$old_IFS     # restore default field separator 
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.