how to fetch the data of column from txt file without column name in unix?

Viewed 222

This is student.txt file:

RollNo|Name|Marks
123|Raghu|80
342|Maya|45
561|Gita|56
480|Mohan|71

I want to fetch data from "Marks" column and I used awk command

awk -F "|" '{print $3}' student.txt

and it gives the output like

Marks
80
45
56
71

This output included column name that is "Marks" but I only want to fetch the data and show the output like

80
45
56
71
5 Answers

Add a condition to your awk script to print the third field if the input record number is greater 1:

awk -F'|' 'FNR>1{print $3}' student.txt

Could you please try following, this has NOT hard coded field number for Marks keyword,in headers it will look for that string and will print only those columns which are under Marks, so even your Marks column is in any field number this should work fine. Written and test in https://ideone.com/Ufq5E2 link.

awk '
BEGIN{ FS="|" }
FNR==1{
  for(i=1;i<=NF;i++){
    if($i=="Marks"){ field=i }
  }
  next
}
{
  print $field
}
'  Input_file

to fetch data from "Marks" column - -use[ing] awk:

$ awk -F\| '
FNR==1 {
    for(i=1;i<=NF;i++)
        if($i=="Marks")
            next
    exit
}
{
    print $i
}' file
80
45
56
71

Another example:

awk -F'|' 'NR != 1 {print $3}' input_file

a non-awk alternative

$ sed 1d file | cut -d\| -f3

80
45
56
71
Related