Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

Suppose I have a pipe separated file like:

|Sr|Fruits|Colors|
|1 |apple |red|
|2 |orange |orange
|3 |grapes |purple|

Here it is evident using awk that, $2 is Fruits and $3 is the colors column.

In future if the order of the columns change, is it possible to determine the column number using the string?

I.e Colors is $3 and Fruits is $2?

share|improve this question
    
For future information, with the exception of the 3rd line, your file has 5 fields, not 3. A field is defined by the field separator so |foo|bar| is actually 4 fields but the 1st and 4th are empty. To have two fields, you would want foo|bar. –  terdon yesterday

3 Answers 3

up vote 2 down vote accepted

You can try:

$ awk -F'|' '
{
  for(i=1;i<=NF;i++) {
    if($i == "Fruits")
      printf("Column %d is Fruits\n", i-1)
    if($i == "Colors")
      printf("Column %d is Colors\n", i-1)
  }
  exit 0
}
' file
Column 2 is Fruits
Column 3 is Colors

A note that the actually column for Fruits and Colors are $3 and $4.

share|improve this answer

List all column headers:

awk 'BEGIN{ FS="|" }
     { for(fn=1;fn<=NF;fn++) {print fn" = "$fn;}; exit; }
    ' file

Output:

$1 = 
$2 = Sr
$3 = Fruits
$4 = Colors
$5 = 

Using the label-text, print the colmns of your choice, in the order you choose:

awk 'BEGIN{ FS="|" }
     NR==1 { split(columns, c) 
             for(fn=1;fn<=NF;fn++) hdr[$fn]=fn; next; }
     { printf( FS ); for (text in c) printf( "%s", $hdr[c[text]]FS ); print "" }
    ' columns="Colors|Fruits" file

Output:

|red|apple |
|orange|orange |
|purple|grapes |
share|improve this answer

Maybe it is better to print all the columns present in the first row, in order to check not only for these two fields, but also detecting new columns, their names, order changes, etc.

awk -F'|' ' { for (i = 1; i <= NF; ++i) print i, $i; exit } ' file

output:

1
2 Sr
3 Fruits
4 Colors
5
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.