With GAWK 4, you can preserve the field separators by explicitly splitting a string (or the whole line) and iterating over the result of the split (fields and separators) for output.
This example uses FPAT
(a regex specifying the field structure) and patsplit()
but could use FS
(a regex specifying the field separator or containing a single space to represent [ \t\n]+
) and split()
instead.
gawk "v=$value" '{n = patsplit($0, arr, FPAT, seps); arr[11] = v; for (i = 0; i <= n; i++) {printf "%s%s", a[i], seps[i]}; print ""}'
Note that a[0]
will always be null, seps[0]
will contain any leading separator and seps[n]
will be any separator characters (whitespace) at the end of the input line.'
Here is the oneliner in a more readable form:
gawk "v=$value" '
{
n = patsplit($0, arr, FPAT, seps);
arr[11] = v;
for (i = 0; i <= n; i++) {
printf "%s%s", a[i], seps[i]
};
print ""
}'