Awk - Text Processing - Layout Functions
Written by Wim Stockman - on 06 Oct 2020 - last updated on 22 Feb 2021
When starting in gopherspace one might craft some simple tools to align monospaced text. I crafted my little simple text processing tools with Awk.
Awk is by far my favourite little tool in Linux. Now in the gemini space this might seem less relevant but it still shows the power of these ancient tools that existed far before the 21th century.
These are 3 align functions, giving we have a fixed number of characters on a line.
- Right align is leftfill function
- Center text is centertext :-)
- Left align which is rightfill
1. Leftfill
This function leftfills a text with your character of choice, a paddingchar:
Example:
-----------------------------------------------------------------HelloWorld
Usage: leftfill(HelloWorld,75,"-");
CodeSnippet:
function leftfill(text,width,paddingchar){
if(!paddingchar){paddingchar=" ";}
size=length(text)+1;
out="";
for(i=size;i<=width;i++){ out = out paddingchar;}
out = out text;
paddingchar=" " ;
print(out);
}
Which fills up the left side of your text with a paddinchar.
Default Paddingchar is <space>
2. Centertext
This function centers the text in your giving width
Example:
-------------------------------Center Text--------------------------------
Usage: centertex(text,width,"-")
CodeSnippet:
function centertext(text,width,paddingchar) {
size=length(text);
out="";
insertpos=int((width-size)/2);
if(!paddingchar){paddingchar=" ";}
for(i=0;i<=width;i++)
{
if(i==insertpos) {out= out text; i=i+size}
else { out = out paddingchar; }
}
print(out);
}
and you can add a paddingchar to fill up both left and rigt side
Default Paddingchar is <space>
3. Rightfill
This Functions Rightfills with a paddingchar.
Right Fill----------------------------------------------------------------
Usage: rightfill(Text,75,"-");
CodeSnippet:
function rightfill(text,width,paddingchar) {
if(!paddingchar){paddingchar=" ";}
size=length(text)+1;
out=text;
for(i=size;i<=width;i++){ out = out paddingchar;}
paddingchar=" " ;
print(out);
}
Which fills up the right side of your text with a paddinchar.
Default Paddingchar is <space>
Usage
To Use these awk function inside your awk scripts you can copy and paste them
or save them to a file:e.g. layout_func.awk
and include them with the:
@include layout_func.awk
To use it on the command line for example creating a cool gopher page Title
you can use it:
awk -f layout_func.awk '{centertext($0,75,"-")}'