November 18, 2023

awk Case Study - 10

Formats its input into lines that are at most 60 characters long

# fmt - format
# input: text
# output: text formatted into lines of <= 60 characters

awk '/./ { for (i = 1; i <= NF; i++) addword($i) }
/^$/ { printline(); print "" }
END { printline() }

function addword(w) {
    if (length(line) + length(w) > 60)
        printline()
        line = line " " w
    }
function printline() {
    if (length(line) > 0) {
        print substr(line, 2)
        line = ""
    }
}' long.txt  

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.