2

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?

D-Klotz
  • 1,973
  • 1
  • 15
  • 37

4 Answers4

5

You could use printf

printf "%.2048s\n", $2
user000001
  • 32,226
  • 12
  • 81
  • 108
  • Thanks for this. Since there haven't been any red flags brought up with my substr($2, 1, 2048), I'm going to stick with that for now. I am using a simple "print a, b, c, d" that is very long and I'd rather not restructure it with a printf if i don't need to. Thanks again. – D-Klotz Feb 27 '14 at 19:29
2

Alternate way:

printf "%.2048s", $2
anubhava
  • 761,203
  • 64
  • 569
  • 643
1

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 
fedorqui
  • 275,237
  • 103
  • 548
  • 598
  • I won't be able to use this trick. It's clever I'll grant that. In my case I have two audit log files I am processing with many fields of all different types and sizes. – D-Klotz Feb 27 '14 at 19:16
  • OK! If you need to use `FS` and `NF` in other parts, then my approach won't help, sure. – fedorqui Feb 27 '14 at 19:21
1

How about native bash parameter slicing

printf "%s" ${2:0:2048}
iruvar
  • 22,736
  • 7
  • 53
  • 82