Find the answer to your Linux question:
Results 1 to 4 of 4
Enjoy an ad free experience by logging in. Not a member yet? Register.
  1. #1

    add header and footer to many files


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

    My attempt was:
    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:
    find *.cpp -exec cat "header.c {} footer.c > {}.new" \;
    cat: header.c File.cpp footer.c > No such file or directory
    I could just write a small program to do it, but then I'll learn nothing about linux.


  2. #2
    Well, I did it like this:
    prompt> find *.cpp -print0 | xargs -0 -I file echo "cat header.c file footer.c >" >
    prompt> chmod a+x
    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
    Seattle, WA, USA
    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:
    for file in *.cpp; do
        cat header.c "$file" footer.c > "$"
    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:
    find *.cpp -print0 | xargs -0 -I file cat header.c file footer.c >
    This will use xargs to print out each file into "".

  4. $spacer_open
  5. #4
    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