Convert rows into columns and create table with awk

Hello
I've four fields . They are First Name, Last Name, Age, Country. So when I run a Unix command, I get below output with these fields comes every time in different order as you can see. Some times first name is the first row and other time last name is first row in the output and etc etc.. Now I am looking for to have a table with these 4 columns. Let's say first column is First Name, 2nd column is Last Name, 3rd is Age and 4th Column is Country. How can I able to achieve this with awk command or any other unix command? Need your help please. Thank you in advance

Current Output:

First Name: John
Last Name: Slater
Age: 31
Country: USA

Last Name: Watt
Age: 35
Country: UK
First Name: Mark

Country: Germany
First Name: Jim
Age: 50
Last Name: Peterson

Final Output should look like below table:

First Name   Last Name                          Age     Country
John                Slater                                  31         USA
Mark                Watt                                    35          UK
Jim                  Peterson                              50         Germany

Hi rprpr,

unix.com is not a place where the members do your work for you, regardless of if it is homework, personal or professional work.

We are here to help you do your work, not do your work for you.

Why would you post a "problem" which looks like a typical school question which requires an "urgent reply" saying "it must be awk or any other unix command" without any details of the computer technology available to you and what code you have written or tried so far? Urgent why? Because your teacher told you to have the homework done in two days? Urgent because why? Urgent because you took a computer admin job and have no idea how to create a basic computer program?

Have you ever written a single line of software?

We are not here to beg you to provide basic technology details and we are not here to do you work for you.

So, if you want help, you need to be very technically specific.

Thanks.

1 Like

------ Post updated at 03:06 AM ------

I apologize. the "urgent" word came out there by mistake.. i used awk command to create the table and print the values but as you can see that in original output, the fields are arrangee in different orders, hence the columns comes with different values (i.e. columns not matching with its actual fields values). It doesn't need to be awk specially, it can be any command..

In addition to what Neo has already said, it isn't at all clear what you are really trying to do. Since features vary from system to system and shell to shell, you should always tell us what operating system and shell you're using when starting a thread in the Shell Programming and Scripting forum. You haven't done that.

You haven't shown us what your original input looks like. If you're trying to rewrite your awk script to produce the output you want instead of the current output you showed us in post #1 in this thread, we need to know details about your input file(s) format(s).

You haven't shown us the awk script that produces your current output. If you want us to help you fix your code, we have to be able to see your code.

If you want to keep your current awk script and write another shell, sed , awk , or some other utility or combination of utilities; we could do that, but it would be grossly inefficient and would seem to be fighting against your goal of directly producing the final output you want. Whether or not you have tried to write a script to reformat your current output and want to rewrite your script to format your output correctly to start with, we need to see what you have tried to achieve that goal so we have a better understanding of what you do understand and where you're stuck.

So, please help us help you by:

  1. telling us what operating system you're using,
  2. telling us what shell you're using,
  3. showing us the input data (in CODE tags) that was used by your awk script to produce the current output you have shown us and explain to us in English the format of that input data,
  4. showing us your awk script (in CODE tags) that processed the input data described above and produced the current output you have shown us,
  5. showing us code that you have tried (in CODE tags) to get the final output you are hoping to produce, and
  6. explaining to us where you are stuck.
1 Like
awk -v cols="First Name:Last Name:Age:Country" '
BEGIN {
  col_count=split(cols, col_arr, ":");
  for (i=1; i<=col_count; i++) printf col_arr ((i==col_count) ? "\n" : "\t");
}
{
  for (i=1; i<=NF; i++) {
     sub("[ \t]*:[ \t]", ":", $i);
     split($i, value_pair, " *: *");
     slabel[value_pair[1]]=value_pair[1];
     data[value_pair[1]]=value_pair[2];
  }
  for (i=1; i<=col_count; i++) printf data[slabel[col_arr]] ((i==col_count) ? "\n" : "\t");
} ' FS="\n" RS="\n\n" infile

Thank you so much rdrtx1 for your help. I still see one issue when the total no. of fields are not equal (i.e.4 fields) for every section.. This is the output results I'm getting after I run command..Here you can see Last name is repeating for all 3 rows and Age 50 is also repeating in this below results

First Name   Last Name   Age   Country
John F         Slater           31    USA
Mark           Slater           35     United Kingdom
Jim             Slater           50     Germany
Mike           Crown           50     Canada

This is my original input file:

First Name: John F
Last Name: Slater
Age: 31
Country: USA

Last Name: Watt
Age: 35
Country: United Kingdom
First Name: Mark

Country: Germany
First Name: Jim
Age: 50

Country: Canada
Last Name:  Crown
First Name: Mike

Can you guys please suggest how to make this happen? Thank you

------ Post updated at 02:21 AM ------

I was running this below awk command initially in the first place...But this is not working either..

cat infile.txt | awk '
                        BEGIN {printf("FIRSTNAME LASTNAME AGE COUNTRY\n")
                                        }
                        /First Name:/ {F=$3$4}
                        /Last Name:/ {L=$3}
	        /Age:/ {A=$2}
                        /Country/ {print F, L, A, $2$3}' | column -t

=======================

The output results I get by running above awk command. How can I fix this? Please help. Thanks

FirstName LastName Age Country
JohnF Slater      USA
JohnF Slater   United Kingdom
Mark Slater  Germany
Jim Slater Canada

If you want our help, you would do well to provide the information we need to help you (such as was requested two days ago in post #4 in this thread. Since you have chosen to withhold much of the information requested, I will show you code that works with the ksh , awk , and column that are available on macOS High Sierra version 10.13.6. If there are any changes needed to work in your environment, it will be up to you to figure out what changes are needed.

Note that I added the "none given" as data to fill fields that contained no data in an input record because the version of column on my system doesn't seem to recognize two adjacent field separators as delimiters for an empty field.

I have no idea where the Last Name "Peterson" that you said should appear in the last line of your output came from. That name does not appear anywhere in any of the sample input files you have shown us. And, since there were four records in your sample input, I do not understand why your desired sample output only contained three records (not counting the header record).

On my system, when file contains the sample input you provided in post #6, the following code:

#!/bin/ksh
awk '
BEGIN {	FS = ": |\n"
	OFS = ":"
	RS = ""
	print FNn = "First Name", LNn = "Last Name", An = "Age", Cn = "Country"
}
{	A = C = F = L = "none given"
	for(i = 1; i <= NF; i += 2) {
		if($i == An)
			A = $(i + 1)
		else if($i == Cn)
			C = $(i + 1)
		else if($i == FNn)
			F = $(i + 1)
		else if($i == LNn)
			L = $(i + 1)
	}
	print F, L, A, C
}' file | column -s: -t

produces the output:

First Name  Last Name   Age         Country
John F      Slater      31          USA
Mark        Watt        35          United Kingdom
Jim         none given  50          Germany
Mike         Crown      none given  Canada

Note that the last name "Crown" in the last output record is misaligned because there is an extraneous <space> character before "Crown" in your sample input file.

Try also

awk -F: -v OFS="\t" '
BEGIN                   {HD      = "First Name	Last Name	Age	Country"
                         for (MX=n=split (HD, HDArr, OFS); n>0; n--) SRCH[HDArr[n]]
                         print HD
                        }

$1 in SRCH              {RES[$1] = $0
                         sub ($1 FS " *", "", RES[$1])
                        }

/^ *$/                  {for (i=1; i<=MX; i++) printf "%s%s", RES[HDArr], (i == MX)?ORS:OFS
                         split ("", RES)
                        }

END                     {for (i=1; i<=MX; i++) printf "%s%s", RES[HDArr], (i == MX)?ORS:OFS
                        }
' file
First Name	Last Name	Age	Country
John F	Slater	31	USA
Mark	Watt	35	United Kingdom
Jim		50	Germany
Mike	Crown		Canada

Thank you so much Don Cragun.. Appreciate your help.. I'll test this out tomorrow.

------ Post updated at 01:58 AM ------

Thank you so much RudiC.. Appreciate your help.. I'll also test this out.

Please be aware that above proposal can handle any (up to system limits) number of fields by just adding the respective labels to the header string.