I would like to remove all of the empty lines from a file, but only when they are at the end/start of a file (that is, if there are no non-empty lines before them, at the start;
A bash solution.
Note: Only useful if the file is small enough to be read into memory at once.
[[ $(
$( reads the entire file and trims trailing newlines, because command substitution ($(....)) implicitly does that. =~ is bash's regular-expression matching operator, and =~ ^$'\n'*(.*)$ optionally matches any leading newlines (greedily), and captures whatever comes after. Note the potentially confusing $'\n', which inserts a literal newline using ANSI C quoting, because escape sequence \n is not supported.&& is always executed.BASH_REMATCH rematch contains the results of the most recent regex match, and array element [1] contains what the (first and only) parenthesized subexpression (capture group) captured, which is the input string with any leading newlines stripped. The net effect is that ${BASH_REMATCH[1]} contains the input file content with both leading and trailing newlines stripped.echo adds a single trailing newline. If you want to avoid that, use echo -n instead (or use the more portable printf '%s').