Wednesday, August 17, 2011

padding variables in bash

This is a quick, but very helpful little script I found out on the net for padding variables.

#!/bin/bash


function lpad
{
word="$1"
while [ ${#word} -lt $2 ]; do
word="$3$word";
done;
echo "$word";
}

function rpad {
word="$1"
while [ ${#word} -lt $2 ]; do
word="$word$3";
done;
echo "$word";
}

lpad 3 5 0

rpad fooby 20 ^

Monday, March 7, 2011

Finding Blank spaces and fields in awk and perl

I recently was working on a project where the customer wanted to create a report that would print the values of one field if another field was blank. Specifically for this case if field 24 is blank then print the value in field 2. I believe that this particular case was for claimants in insurance records, but it could just as easily have been cell phone, vs main phone, or primary vs secondary address.
Anyway here's the regular expression to search for fields that are completely blank. Note the ^ at the start and the $ at the end to specify both the beginning as well as the ending of the field and the []* referring to empty brackets.


##-- this checks if $24 has any number of blanks in it ##
if ($24 ~ /^[ ]*$/)
{
printf("%s|",$2);
}
else
{
printf("%s|",$24);
}


This same piece of regular expression should work pretty well for Perl with a matching test, but I'd tr it out before I swear to it.