Find the answer to your Linux question:
Results 1 to 4 of 4
Hello, I'm trying to add a header to many .cpp files in a directory (or directory tree). My attempt was: Code: find *.cpp -exec cat header.c {} footer.c > {}.new ...
Enjoy an ad free experience by logging in. Not a member yet? Register.
  1. #1
    Just Joined!
    Join Date
    Aug 2010
    Posts
    3

    add header and footer to many files


    Hello,

    I'm trying to add a header to many .cpp files in a directory (or directory tree).

    My attempt was:
    Code:
    find *.cpp -exec cat header.c {} footer.c > {}.new \;
    But the second {} is not replaced by the filename, instead the output of cat will go to a file named "{}.new".

    If I put part of the command inside quotes the substitution occurs, but then I get other errors like:
    Code:
    find *.cpp -exec cat "header.c {} footer.c > {}.new" \;
    cat: header.c File.cpp footer.c > File.cpp.new: No such file or directory
    I could just write a small program to do it, but then I'll learn nothing about linux.

    Thanks.

  2. #2
    Just Joined!
    Join Date
    Aug 2010
    Posts
    3
    Well, I did it like this:
    Code:
    prompt> find *.cpp -print0 | xargs -0 -I file echo "cat header.c file footer.c > file.new" > run.sh
    prompt> chmod a+x run.sh
    prompt>./run.sh
    But it seems a bit clumsy and not elegant.
    I'm still waiting for suggestions.

  3. #3
    Linux Guru Cabhan's Avatar
    Join Date
    Jan 2005
    Location
    Seattle, WA, USA
    Posts
    3,252
    I think the real problem here is "find". You want to redirect your output to various files, but "> FILE" is interpreted by Bash, not find.

    So I think you should combine find with a Bash feature. In this case, you're not using any particularly complicated find features, so I'll switch to using Bash globs:
    Code:
    #!/bin/bash
    
    IFS=$'\012'
    
    for file in *.cpp; do
        cat header.c "$file" footer.c > "$file.new"
    done
    The declaration of IFS protects us against spaces in the filename, and we simply loop over every file.

    If you want to use find and xargs, you could do this:
    Code:
    find *.cpp -print0 | xargs -0 -I file cat header.c file footer.c > file.new
    This will use xargs to print out each file into "file.new".

  4. #4
    Just Joined!
    Join Date
    Aug 2010
    Posts
    3
    Thanks Cabhan,

    This loop example using the bash will help me with other tasks too.

Posting Permissions

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