FIELDWIDTH, I believe is specific to gawk which I find enormously
useful in dealing with fixed width fields without any field
delimiters. How do I simulate the same on other versions of awk?
Sometimes, I'm not allowed to load gawk on some sytems and hence this
portability question.
regards,
Sivaram
use the substr() function to define fields.
e.g.:
a=$0
$1=substr(a,1,2)
$2=substr(a,3,3)
$3=substr(a,7,2)
.
.
.
Chuck Demas
--
Eat Healthy | _ _ | Nothing would be done at all,
Stay Fit | @ @ | If a man waited to do it so well,
Die Anyway | v | That no one could find fault with it.
de...@theworld.com | \___/ | http://world.std.com/~cpd
[...]
When using awk on platforms where gawk is not available (for whatever
reason) and where I need to use fixed width fields I use the following
awk function (sorry that lines wrap in posting):
function setFieldsByWidth( i,n,FWS,start,copyd0) {
# Licensed under GPL Peter S Tillier, 2003
# NB corrupts $0
copyd0 = $0 # make copy of $0 to work on
if (length(FIELDWIDTHS) == 0) {
print "You need to set the width of the fields that you require" >
"/dev/stderr"
print "in the variable FIELDWIDTHS (NB: Upper case!)" >
"/dev/stderr"
exit(1)
}
if (!match(FIELDWIDTHS,/^[0-9 ]+$/)) {
print "The variable FIELDWIDTHS must contain digits, separated" >
"/dev/stderr"
print "by spaces." > "/dev/stderr"
exit(1)
}
n = split(FIELDWIDTHS,FWS)
if (n == 1) {
print "Warning: FIELDWIDTHS contains only one field width." >
"/dev/stderr"
print "Attempting to continue." > "/dev/stderr"
}
start = 1
for (i=1; i <= n; i++) {
$i = substr(copyd0,start,FWS[i])
start = start + FWS[i]
}
}
Note that the "/dev/stderr" entries in some lines have wrapped.
I then call setFieldsByWidth() in my main awk code as follows:
BEGIN {
FIELDWIDTHS="7 6 5 4 3 2 1" # for example
}
!/^[ ]*$/ {
saveDollarZero = $0 # if you want it later
setFieldsByWidth()
# now we can manipulate $0, NF and $1 .. $NF as we wish
print $0, NF
next
}
1
or something similar. It has worked OK for me quite a few times.
It's a workaround.
HTH
--
Peter S Tillier
"Who needs perl when you can write dc, sokoban,
arkanoid and an unlambda interpreter in sed?"