LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   Bash- grep and loops (http://www.linuxquestions.org/questions/programming-9/bash-grep-and-loops-4175429421/)

calvarado777 09-28-2012 07:07 AM

Bash- grep and loops
 
Hello all, I am in week two of learning Bash and I am lost!
My first task is to search the current directory for files with the extensions .c and .cc, and search for the strings printf and fprintf within those files. IF the print statements are found, then I am to add in a header if it's not already there.

This is where I am at so far-- I am finding the man pages hard to understand and googling everything has become overwhelming!

Can anyone maybe just give me a few hints? My errors that I have run into so far is that I can't seem to get the right syntax when I am piping my 'ls' results to my grep in the outer for loop...so I eventually decided to work from the inside out...but now I can't seem to get the right type of arguements for my inner grep :-(

Code:

#!/bin/sh

for FILE in `ls *.cc *.c` # | egrep "printf\ | fprintf"

do
        echo $FILE;                                    #to make sure ls worked
        if [ grep -Fqx '#include <stdio.h>' "$FILE" ] 
        then
                sed '1i\
                #include <stdio.h> ' file > new_file;
                mv new_file file;
        fi
done


Toggan 09-28-2012 08:54 AM

You may want to try using exit codes for your if statement. Something along the lines of:

grep -Fqx '#include <stdio.h>' $FILE
if [[ $? -eq 0 ]]; then
sed '1i\
#include <stdio.h> ' file > new_file;
mv new_file file;
fi

This will do the quiet grep, and then only continue if the command was successful. If you'd like some error checking, you could put an else before the fi and echo error or something.

crabboy 09-28-2012 09:23 AM

Please post your thread in only one forum. Posting a single thread in the most relevant forum will make it easier for members to help you and will keep the discussion in one place. This thread is being closed because it is a duplicate.

Follow thread here: http://www.linuxquestions.org/questi...ps-4175429419/


All times are GMT -5. The time now is 05:02 PM.