Skip to content

Instantly share code, notes, and snippets.

@Micrified
Created April 14, 2022 12:27
Show Gist options
  • Save Micrified/58302fe03f98a467703de6199cd32e72 to your computer and use it in GitHub Desktop.
Save Micrified/58302fe03f98a467703de6199cd32e72 to your computer and use it in GitHub Desktop.
AWK - Utility to fold lines preserving words
#!/bin/sh
sed 's/ / /g' $* |
awk '
BEGIN {
N = 40
FT = "[ ]"
}
{
offset = 0
n = 0
for (f = 1; f <= NF; f++)
{
# Case: Line non-zero and adding next character might overboard
if (n > 0 && (n + length($f) + 1) > N) {
n++
printf "%s\n", substr($i, offset, n)
offset += n
n = 0
}
# Increment length
n += length($f)
# Case: While field longer than line limit, cut down
while (n > N) {
printf "%s\n", substr($i, offset, N)
offset += N
n -= N
}
}
printf "%s\n", substr($i, offset, n)
}
'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment