10

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

5 Answers 5

17

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

2
  • Adding | vim - in the end will allow you to navigate/grep through text and also highlight syntax if needed, so find . -name "*.java" -exec cat {} \; | vim -
    – graceman9
    Oct 27, 2019 at 23:41
  • To see the file name and to see more easily where a file ends: find "$1" -type f -print -exec cat {} \; -exec echo "###" \; Apr 22, 2022 at 7:45
9
find . -name "*.java" -print0 | xargs -0 cat 
2
  • 1
    The {} \; is not needed after cat ... those are used only in find's -exec command.
    – cottonke
    Jan 10, 2013 at 15:25
  • ^^ Right. corrected...
    – anishsane
    Jan 10, 2013 at 15:47
4
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
1
find . -name "*.java" -exec cat {} \;
1
 grep -R -win --include='*\.java' '' * | less

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .