How do I concatenate multiple files in multiple directories with their names?
I have multiple files that contain codes, and am trying to merge them in order to print it out. They spread out in multiple directories.
For example, I have directories like:
root
/ \
dir1 dir2
/ \ / \
s1 s2 s3 s4
which each contain files, to be concatenated into one text file.
Final output would look like:
Filename(its directory name)
content
Filname 2 (its directory name)
content 2
.
.
.
Filename n (its directory name)
content n
Can someone help me achieve this using command line?
Provided that "in order" means in your locale's collation order, you can use simple shell globs.
Ex. given
$ tree root
root
├── dir1
│ ├── s1
│ └── s2
└── dir2
├── s3
└── s4
2 directories, 4 files
then
$ for f in root/*/*; do { printf '%s (%s)\n' "${f##*/}" "${f%/*}"; cat "$f"; printf '\n'; }; done
s1 (root/dir1)
Contents of file 1
s2 (root/dir1)
Contents of file 2
s3 (root/dir2)
Contents of file 3
s4 (root/dir2)
Contents of file 4
If you just need something quick'n'dirty and don't need that specific format, then you could use head
with a number of lines that is larger than the known line count of any of your files:
$ head -n 100000 root/*/*
==> root/dir1/s1 <==
Contents of file 1
==> root/dir1/s2 <==
Contents of file 2
==> root/dir2/s3 <==
Contents of file 3
==> root/dir2/s4 <==
Contents of file 4