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.
- 08-27-2010 #1Just 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:
But the second {} is not replaced by the filename, instead the output of cat will go to a file named "{}.new".Code:find *.cpp -exec cat header.c {} footer.c > {}.new \;
If I put part of the command inside quotes the substitution occurs, but then I get other errors like:
I could just write a small program to do it, but then I'll learn nothing about linux.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
Thanks.
- 08-27-2010 #2Just Joined!
- Join Date
- Aug 2010
- Posts
- 3
Well, I did it like this:
But it seems a bit clumsy and not elegant.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
I'm still waiting for suggestions.
- 08-29-2010 #3
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:
The declaration of IFS protects us against spaces in the filename, and we simply loop over every file.Code:#!/bin/bash IFS=$'\012' for file in *.cpp; do cat header.c "$file" footer.c > "$file.new" done
If you want to use find and xargs, you could do this:
This will use xargs to print out each file into "file.new".Code:find *.cpp -print0 | xargs -0 -I file cat header.c file footer.c > file.new
- 08-30-2010 #4Just Joined!
- Join Date
- Aug 2010
- Posts
- 3
Thanks Cabhan,
This loop example using the bash will help me with other tasks too.


Reply With Quote
