I have multiple text files (tab delimited) - all with four columns - id, name, salary and department.
Column order in each txt file is not guarenteed.
I need to write a Korn shell script which takes one of the file name as input and returns id and department columns as output.
I am not sure about how to return those two specific columns considering that the order of those two columns is not same for the input file that gets passed and so I am assuming I cannot use fixed ordinal position (like $1 or $3..). Is there a way I can read the data from file based on column names instead of ordinal positions (my input text file can contain column headers).
Any help in this regard would be greatly appreciated. Thanks!
It's pretty straight forward to treat the first record of the input file as a header and use those labels to identify the columns. This assumes that there aren't any spaces in the headers:
awk '
NR == 1 {
for( i = 1; i <= NF; i++ ) # create map, column name to number
col[$(i)] = i;
next;
}
# for all other records, print the desired data from the columns
{ printf( "%s %s\n", $(col["Name"]), $(col["Mangerid"]) ); }
' input-file >output-file
Do not post classroom or homework problems in the main forums. Homework and coursework questions can only be posted in this forum under special homework rules.
Please review the rules, which you agreed to when you registered, if you have not already done so.
More-than-likely, posting homework in the main forums has resulting in a forum infraction. If you did not post homework, please explain the company you work for and the nature of the problem you are working on.