Find the answer to your Linux question:
Results 1 to 2 of 2
I am writing a script that finds all files (in the pwd) that have the .c extension and it searches them for print and pfrintf. If either are found, the ...
  1. #1
    Just Joined!
    Join Date
    Oct 2009
    Posts
    10

    add line to files containing phrase

    I am writing a script that finds all files (in the pwd) that have the .c extension and it searches them for print and pfrintf. If either are found, the line #include <stdio.h> is added, unless it's already there.

    I am using egrep -c 'f?printf' *.c | cut -d: -f 2 to determine whether there are any occurrences, and then I'll do echo "#include <stdio.h>\n$(cat file)" > temp" and "mv temp file". The trouble is that I don't know what file should be.

    I was planinng on using a shell script but should I be using sed instead?

  2. #2
    Linux User
    Join Date
    May 2008
    Location
    NYC, moved from KS & MO
    Posts
    251
    Quote Originally Posted by blackbox111 View Post
    I am writing a script that finds all files (in the pwd) that have the .c extension and it searches them for print and pfrintf. If either are found, the line #include <stdio.h> is added, unless it's already there.

    I am using egrep -c 'f?printf' *.c | cut -d: -f 2 to determine whether there are any occurrences, and then I'll do echo "#include <stdio.h>\n$(cat file)" > temp" and "mv temp file". The trouble is that I don't know what file should be.

    I was planinng on using a shell script but should I be using sed instead?
    You are right about using sed, but you don't need to use temp file. sed supports inline editing (option -i).

    Code:
    find . -iname "*.c"|while read file; do [ `egrep f?printf $file` ] && sed -i '1i\
    #include <stdio.h>' $file; done
    Yet a simpler version would be
    Code:
    egrep -l f?printf *.c | while read file; do sed -i '1i\
    #include <stdio.h>' $file; done
    if you only care about all .c files under current directory excluding all sub-directories.
    Last edited by secondmouse; 11-03-2009 at 05:31 AM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...