jaam
jaam

Reputation: 970

Linux: Padding text to fixed length

My text looks like this:

some text..............................12
some more text......................65
even sometext...................................68

In other worlds, it's a TOC. I'd like the lines to be of equal length, say 32 bytes, padded w/ .. How do I do this in Linux? So far I've done everything w/ sed, but I'm not sure about this one

EDIT: I should've probably added that a solution involving any tool / language available on Linux command line is fine

Upvotes: 0

Views: 1577

Answers (1)

John Zwinck
John Zwinck

Reputation: 249133

This awk program will do it:

#!/usr/bin/env awk -f

BEGIN {
    FS = "\\."
    width = 32 # total desired width
    pad = sprintf("%*s", width, "") # " " * width
    gsub(" ", ".", pad) # "." * width
}

{
    padwidth = width - length($1) - length($NF)
    printf("%s%.*s%s\n", $1, padwidth, pad, $NF)
}

Put it in a text file, run chmod +x on that file to make it executable, then run something like this:

./my_awk_script my_input_file

The result for your example input is:

some text.....................12
some more text................65
even sometext.................68

Note: NF is the Number of Fields, so $NF is the last token on a line.

Upvotes: 1

Related Questions