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

后端 未结 16 653
一个人的身影
一个人的身影 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:39

    I'd like to introduce another variant for gawk v4.1+

    result=($(gawk '
        BEGIN {
            lines_count         = 0;
            empty_lines_in_head = 0;
            empty_lines_in_tail = 0;
        }
        /[^[:space:]]/ {
            found_not_empty_line = 1;
            empty_lines_in_tail  = 0;
        }
        /^[[:space:]]*?$/ {
            if ( found_not_empty_line ) {
                empty_lines_in_tail ++;
            } else {
                empty_lines_in_head ++;
            }
        }
        {
            lines_count ++;
        }
        END {
            print (empty_lines_in_head " " empty_lines_in_tail " " lines_count);
        }
    ' "$file"))
    
    empty_lines_in_head=${result[0]}
    empty_lines_in_tail=${result[1]}
    lines_count=${result[2]}
    
    if [ $empty_lines_in_head -gt 0 ] || [ $empty_lines_in_tail -gt 0 ]; then
        echo "Removing whitespace from \"$file\""
        eval "gawk -i inplace '
            {
                if ( NR > $empty_lines_in_head && NR <= $(($lines_count - $empty_lines_in_tail)) ) {
                    print
                }
            }
        ' \"$file\""
    fi
    

提交回复
热议问题