Removing trailing / starting newlines with sed, awk, tr, and friends

后端 未结 16 943
一个人的身影
一个人的身影 2021-01-30 21:04

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;

16条回答
  •  眼角桃花
    2021-01-30 21:34

    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.
    • Note that this particular regex always matches, so the command after && is always executed.
    • Special array variable 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.
    • Note that printing with echo adds a single trailing newline. If you want to avoid that, use echo -n instead (or use the more portable printf '%s').

提交回复
热议问题