Skip to main content
replaced http://unix.stackexchange.com/ with https://unix.stackexchange.com/
Source Link

This answerThis answer shows how you can determine the maximum data length for each field.

This answer shows how you can determine the maximum data length for each field.

This answer shows how you can determine the maximum data length for each field.

Source Link

Note: all of the below (obviously) assume that the uid: line will always be the last one of each group.  However, they all work with % characters in the data.

If you want to save up all the data and print it at the end, here’s a somewhat simple approach, using arrays:

awk 'BEGIN {count=0}
     /mail:|fullName:|uid:/ {s[count] = s[count] ", " $0} /uid:/ {count++}
     END {for (i=0; i<count; i++) print substr(s[i],3)}' dump2.txt

If you want to be able to handle the fields individually (at the end), use a two-dimensional array:

awk 'BEGIN {count=0}
     /mail:|fullName:|uid:/ {s[count][$1] = $0} /uid:/ {count++}
     END {for (i=0; i<count; i++) printf "%s, %s, %s\n",
                s[i]["mail:"], s[i]["fullName:"], s[i]["uid:"]}' dump2.txt

(Like glenn’s answer, this assumes that the mail:, fullName:, and uid: strings appear as the first field in the line.)

I don’t know what you meant when you mentioned alignment, but, from here, it’s easy to line up the fields in your output:

awk 'BEGIN {count=0}
     /mail:|fullName:|uid:/ {s[count][$1] = $0} /uid:/ {count++}
     END {for (i=0; i<count; i++) printf "%23s, %23s, %s\n",
                s[i]["mail:"], s[i]["fullName:"], s[i]["uid:"]}' dump2.txt

or

awk 'BEGIN {count=0}
     /mail:|fullName:|uid:/ {s[count][$1] = $0} /uid:/ {count++}
     END {for (i=0; i<count; i++) printf "%-23s, %-23s, %s\n",
                s[i]["mail:"], s[i]["fullName:"], s[i]["uid:"]}' dump2.txt

or

awk 'BEGIN {count=0}
     /mail:|fullName:|uid:/ {s[count][$1] = $0} /uid:/ {count++}
     END {for (i=0; i<count; i++) printf "%-23s %-24s %s\n",
                                    s[i]["mail:"] ",",
                                    s[i]["fullName:"] ",",
                                    s[i]["uid:"]}' dump2.txt

This answer shows how you can determine the maximum data length for each field.