I always have to submit the source codes in my printed assignment report. I have to copy and paste my course codes into the document and I find that it is an annoying task.

I want to solve this "copy and paste" problem. Therefore I did it with cat like that but it only works in the current directory. I hope it can display the file contents recursively.

ls -R *.java | xargs cat >> all_course.txt

migrated from stackoverflow.com Jan 10 '13 at 18:42

This question came from our site for professional and enthusiast programmers.


You can use find (man page) to accomplish this:

find -name "*.java" -exec cat {} \;

You can also add a -print before the -exec to print the file name before each cat operation

find . -name "*.java" -print0 | xargs -0 cat 
  • 1
    The {} \; is not needed after cat ... those are used only in find's -exec command. – cottonke Jan 10 '13 at 15:25
  • ^^ Right. corrected... – anishsane Jan 10 '13 at 15:47
shopt -s globstar
cat **/*.java >> all_course.txt

That all_course file will be a bit of a mess. You probably want to add in some headers or footers:

for f in **/*.java; do
    echo "/* *********************************"
    echo " * $f"
    echo " * *********************************/"
    echo ""
    cat "$f"
    echo ""
    echo "/* *********************************"
    echo " * $f"
    echo " * *********************************/"
    echo ""
    echo ""
done > all_course.txt
find . -name "*.java" -exec cat {} \;
 grep -R -win --include='*\.java' '' * | less

Will show line no. also, for easy reading. Manipulate with grep switches for better results.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.