AWK command to cut the desired header columns

Hi Friends,

I have a file1

i want to retrieve only the fields which have DEP,CITY,TRANS as headers in other file.

Output:

I want to give the input as DEP,CITY,TRANS column names to get the output.

i used cut command .. but if i have 300 fileds it is more difficult to search for the field names. i want to use AWk commad to get the output

plz help.

Looks very much like home work... No?

Try like..

awk -F\| '{ print $1"|"$3"|"$5}' test1.txt 
awk -F\| -vcols='Dep,City,Trans' '
NR==1 {
for(i=1;i<=NF;i++)
 if(index(cols,$i))
 {
  c=1
  t=(t)?(t FS $i):$i
 }
print t;next
}
{
t=""
for(i=1;i<=NF;i++)
 if (i in c)
  t=(t)?(t FS $i):$i
print t
}' file

@vbe: Thanks for the reply .no its not hme work, i tried with awk and cut but the file which i am getting is not static . so thougth of taking help .

@bmk : Thanks for the reply. yes i tried with same command. but file which i get is dymanic the field position may change :slight_smile:

@Elixir : Thanks for the reply. i will execute and try this now .
@