#! /usr/bin/gawk -f
# Last edited on 2001-01-01 22:36:24 by stolfi
BEGIN {
abort = -1;
usage = ( \
"factor-word-trivial \\\n" \
" [ -v inField=NUM ] \\\n" \
" [ -v erase=BOOL ] \\\n" \
" [ -v outField=NUM ] \\\n" \
" < INFILE > OUTFILE" \
);
# Factors the `inField'th field of INFILE into individual characters
# (by bracketing them with "{}").
# If `erase' is set, the input field is erased, otherwise it is
# preserved. Then inserts the factored word as the "outField"th
# field.
#
if (inField == "") inField = 1;
if (erase == "") erase = 0;
if (outField == "") outField = inField;
}
(abort >= 0) { exit abort; }
/^#/ { print; next; }
/./ {
if (NF < inField) { data_error("not enough input fields"); }
x = $(inField);
y = factor_text_trivial(x);
printout(y, outField, inField, erase);
next;
}
function factor_text_trivial(x)
{
# Wraps each character of `x' in braces.
# Clean up any junk:
gsub(/{[^{}]*}/, "", x);
gsub(/[!]/, "", x);
# Split word into characters:
return gensub(/(.)/, "{\\1}", "g", x)
}
function printout(mw, ofn, ifn, del, i)
{
# prints $0 with "mw" inserted as field "$(ofn)"
# if "del" is true, deletes field "$(ifn)"
if (del)
{ if (NF < ifn)
{ data_error("not enough input fields\n"); }
else
{ for(i=ifn; i<NF-1; i++) { $(i) = $(i+1); }
NF--;
}
}
if (NF < ofn-1) { data_error("not enough output fields\n"); }
if (ofn == 1)
{ print mw, $0; }
else if (ofn == NF+1)
{ print $0, mw; }
else
{ for (i=1;i<ofn;i++) { printf "%s%s", $(i), OFS; }
printf "%s", mw;
for (i=ofn;i<=NF;i++) { printf "%s%s", OFS, $(i); }
printf "\n";
}
}
function data_error(msg)
{
printf "line %d: %s\n", NR, msg >> "/dev/stderr";
abort = 1;
exit 1;
}
function arg_error(msg)
{
printf "%s\n", msg >> "/dev/stderr";
abort = 1;
exit 1;
}