Last night I needed to compile a folder (directory) of text files into a single file with the file name as a header. This simple `bash` script did the work:
% for f in *.txt; do echo “# $f”; cat “$f”; done > ../legends.txt
The hash sign ahead of the filename reveals that I compiled the document as a markdown text. I couldn’t quite figure out how to insert newlines into the script above, so I ended up using some regex to do that: finding instances of the hash tag and inserting a new line before it and then finding instances of .txt and inserting a newline after it. And then, finally, removing the `.txt` extension altogether. From there, I converted the document to HTML that I could format more clearly.
As seen here, I entered the script directly at the command line, but it could also, I suppose be saved thus:
#! /usr/bin/env bash
for f in *.txt;
do echo “# $f”;
I’m not sure how to direct the output into a file within a `bash` script. I usually just do that at the command line. (I know, I know: I need to learn bash scripting. I’ll get there.)