AWK: Is there a way to limit the width of an output field?
Question
I need to limit the final size of a field to 2048. I could probably use:
ACTION_PARAMETER=substr($2,1,2048);
But is there a better way?
Solution
You could use printf
printf "%.2048s\n", $2
OTHER TIPS
Alternate way:
printf "%.2048s", $2
You can play with the field separator FS
being ""
and then limiting the number of fields NF
:
awk 'BEGIN{FS=OFS=""} NF=2048' file
Example with 3 instead of 2048
$ cat a
hello
how are
you
i am ok
$ awk 'BEGIN{FS=OFS=""} NF=3' a
hel
how
you
i a
or even as a parameter:
$ awk -v limit=2 'BEGIN{FS=OFS=""} NF=limit' a
he
ho
yo
i
How about native bash parameter slicing
printf "%s" ${2:0:2048}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow