You can do something like that :
Code:
awk '
BEGIN {
fields_count = split("5,5,5,5,5,5,5,5,5,5,5", fsize, ",");
FS = "|"
OFS = "";
}
function cnv_field(fld ) {
if (length($fld) > fsize[fld]) {
printf("Line %d, field %d is too long (%d > %d)\n", NR, fld, length($fld), fsize[fld]) | "cat >&2";
status = 1;
}
$fld = sprintf("%-5.5s", $fld);
}
{
if (NF != fields_count) {
printf("Line %d, fields count is invalid (%d != %d)\n", NR, NF, fields_count) | "cat >&2";
status = 1;
}
for (f=1; f<=NF; f++) cnv_field(f);
print;
}
END {
exit status;
}
' $1 > $2
The
length of each field is specified in the fields_count assignment. In my code all the fields are 5 characters.
In the output, the
field separator is set to
"" but you can modify it. For example if you want a space modify the OFS assignment :
OFS = " "
Example (assume script file is convert.sh) :
Code:
$ cat input_file
111|22|333|444|555||77|888|9999|000|1
aa|bbbbbb|cc|dd|rr|ff|ggggggg|hh|ii|jjj|hhh
xxx|yyy|zzz
$ convert.sh input_file output_file
Line 2, field 2 is too long (6 > 5)
Line 2, field 7 is too long (7 > 5)
Line 3, fields count is invalid (3 != 11)
$ echo $?
1
$ cat output_file
111 22 333 444 555 77 888 9999 000 1
aa bbbbbcc dd rr ff ggggghh ii jjj hhh
xxx yyy zzz
$
Jean-Pierre.