Find columns in a file based on header and print to new file


 
Thread Tools Search this Thread
Top Forums Shell Programming and Scripting Find columns in a file based on header and print to new file
# 1  
Old 11-25-2016
Find columns in a file based on header and print to new file

Hello,

I have to fish out some specific columns from a file based on the header value. I have the list of columns I need in a different file. I thought I could read in the list of headers I need,
Code:
# file with header names of required columns in required order
headers_file=$2

# read contents of headers_file into array
IFS=$'\n' read -a headers_list < $headers_file

and then loop through the list to pick out each column I need,
Code:
# loop on header list
for header_value in "${headers_list[@]}"
do
   # print current input file
   echo $header_value

   # look for the column in the input file
   awk -v OFS='\t' -v column_header="$header_value" 'NR==1{for (i=1; i<=NF; i++) if ($i==column_header){p=i; break}; next} {print $p}' $input_file > $output_file

done

The above awk does not work and even if it did it would overwrite the data from each previous column found. How do I find all the columns I need and then print all of them in the right order so they all end up in the output file?

The only thing I could think of was to read the header line from $input_file into another array and then loop through $headers_list making a note of the numerical position of the columns I need. In theory, I could use the list of numerical positions to cobble together a cut argument to get the columns I need. That seems like it would be horribly messy syntax and could probably be done with one line of awk from someone who knows what they are doing.

That means it's time to post and ask for help. I found allot of topics like this one, but most of them seemed to find one column by the header value and print it.

In case that makes a difference, the input files I am working have < 200 columns but may have almost any number of rows. The input file is space delimited and the output should be tab delimited, though I could replace space with tab after the fact if necessary.

Suggestions would be greatly appreciated.

LMHmedchem
# 2  
Old 11-25-2016
As no sample files were provided I made some assumptions on their contents. To put you on track:
headers file
Code:
$ cat headers 
H3
H4
H1
H2

input_file
Code:
$ cat input_file 
H1 H2 H3 H4
01 02 03 04
11 12 13 14
21 22 23 24
31 32 33 34

Code:
$ awk 'NR==FNR{a[$0]=NR;next}{for (i in a) printf "%s ", $a[i];print ""}' headers input_file

Output
Code:
H3 H4 H1 H2 
03 04 01 02 
13 14 11 12 
23 24 21 22 
33 34 31 32

These 2 Users Gave Thanks to ripat For This Post:
# 3  
Old 11-25-2016
Note: The order in for (i in a) is arbitrary, so it cannot be used reliably to preserve order. An alternative would be to use a for(i=min;i<=max;i++) loop..
for example:
Code:
awk 'NR==FNR{A[$1]=++c; next} {s=""; for (i=1; i<=c; i++) {if(FNR==1) P[i]=A[$i]; s=s $(P[i]) OFS} print s}' headers input_file

These 2 Users Gave Thanks to Scrutinizer For This Post:
# 4  
Old 11-25-2016
My bad, am I so rusted in awk? Nice catch.
# 5  
Old 11-25-2016
Hi.

From my perspective, this is a csv manipulation problem. Consequently, a simple csv-aware tool seems appropriate. The dataset is transformed to csv format, and the header-name lines are collected into a csv-like string. The named columns are extracted, and the file is converted from csv format to TAB-separated format -- which the OP required,

Collecting these all together in a script and using dataset from ripat:
Code:
#!/usr/bin/env bash

# @(#) s1       Demonstrate extraction of fields, csvtool.

# Utility functions: print-as-echo, print-line-with-visual-space, debug.
# export PATH="/usr/local/bin:/usr/bin:/bin"
LC_ALL=C ; LANG=C ; export LC_ALL LANG
pe() { for _i;do printf "%s" "$_i";done; printf "\n"; }
pl() { pe;pe "-----" ;pe "$*"; }
em() { pe "$*" >&2 ; }
db() { ( printf " db, ";for _i;do printf "%s" "$_i";done;printf "\n" ) >&2 ; }
db() { : ; }
C=$HOME/bin/context && [ -f $C ] && $C dixf sed pass-fail
pe
dixf csvtool

FILE=${1-data1}
E=expected-output.txt
H=headers

pl " Input data file $FILE:"
head $FILE

pl " Input file converted to csv:"
sed -r 's/\s+/,/g' $FILE |
tee t1

pl " Header name file $H, name list:"
head $H
h1=$( paste -s -d, $H )
pe " Header list = $h1"

pl " Expected output:"
cat $E

pl " Results, extract columns, convert csv to TAB-spaced:"
csvtool namedcol $h1 t1 |
tee t2 |
sed -r 's/,/\t/g' |
tee f1

pl " Verify results if possible:"
C=$HOME/bin/pass-fail
[ -f $C ] && $C || ( pe; pe " Results cannot be verified." ) >&2

exit 0

producing:
Code:
$ ./s1

Environment: LC_ALL = C, LANG = C
(Versions displayed with local utility "version")
OS, ker|rel, machine: Linux, 3.16.0-4-amd64, x86_64
Distribution        : Debian 8.6 (jessie) 
bash GNU bash 4.3.30
dixf (local) 1.21
sed (GNU sed) 4.2.2
pass-fail (local) 1.9

csvtool tool for performing manipulations on CSV files from sh... (man)
Path    : /usr/bin/csvtool
Version : - ( /usr/bin/csvtool, 2014-08-06 )
Type    : ELF 64-bit LSB executable, x86-64, version 1 (SYSV ...)
Help    : probably available with --help
Home    : https://github.com/Chris00/ocaml-csv

-----
 Input data file data1:
H1 H2 H3 H4
01 02 03 04
11 12 13 14
21 22 23 24
31 32 33 34

-----
 Input file converted to csv:
H1,H2,H3,H4
01,02,03,04
11,12,13,14
21,22,23,24
31,32,33,34

-----
 Header name file headers, name list:
H3
H4
H1
H2
 Header list = H3,H4,H1,H2

-----
 Expected output:
H3      H4      H1      H2
03      04      01      02
13      14      11      12
23      24      21      22
33      34      31      32

-----
 Results, extract columns, convert csv to TAB-spaced:
H3      H4      H1      H2
03      04      01      02
13      14      11      12
23      24      21      22
33      34      31      32

-----
 Verify results if possible:

-----
 Comparison of 5 created lines with 5 lines of desired results:
 Succeeded -- files (computed) f1 and (standard) expected-output.txt have same content.

The command csvtool can be found in the Debian repository or at github as noted.

@LMHmedchem: with 300 posts, you should know that posting data samples, expected output, and your computing environment will help make replies easier and more likely to be applicable to your situation. Please do that in your future posts.

Best wishes ... cheers, drl
These 3 Users Gave Thanks to drl For This Post:
# 6  
Old 11-25-2016
Quote:
Originally Posted by Scrutinizer
Note: The order in for (i in a) is arbitrary, so it cannot be used reliably to preserve order. An alternative would be to use a for(i=min;i<=max;i++) loop..
for example:
Code:
awk 'NR==FNR{A[$1]=++c; next} {s=""; for (i=1; i<=c; i++) {if(FNR==1) P[i]=A[$i]; s=s $(P[i]) OFS} print s}' headers input_file

Thank you all for the replies.

I can't seem to get the above working.

Here is some data, sorry this is hard to read but I thought it best to leave it in its original single space delimited format.
Code:
name col_1 col_2 col_3 col_4 col_5 col_6 col_7 col_8
name,1 2 1 1 0 1 0 11.75 9.6154
name,2 7 0 0 0 1 0 12.7917 8.6310
name,3 4 1 1 0.6 1 0 18.2769 4.6420
name,4 6 1 1 0 1 0 16.1389 7.7778
name,5 2 2 3 0.833333 1 0 21.5342 4.2924

headers_file,
Code:
col_1
col_6
col_3
col_4
col_8

desired output (in most cases, some columns in the original input will not be in output)
Code:
name	col_1	col_6	col_3	col_4	col_8
name,1	2	0	1	0	9.6154
name,2	7	0	0	0	8.6310
name,3	4	0	1	0.6	4.6420
name,4	6	0	1	0	7.7778
name,5	2	0	3	0.8333	4.2924

When I run the script above by I get,
Code:
col_1 col_1 col_1 col_1 col_1 col_1 
col_6 col_6 col_6 col_6 col_6 col_6 
col_3 col_3 col_3 col_3 col_3 col_3 
col_4 col_4 col_4 col_4 col_4 col_4 
col_8 col_8 col_8 col_8 col_8 col_8

The code suggestion posted by ripat has a similar issue but I haven't posted the results here because of the comment by Scrutinizer about the order of output.

Quote:
Originally Posted by drl
@LMHmedchem: with 300 posts, you should know that posting data samples, expected output, and your computing environment will help make replies easier and more likely to be applicable to your situation. Please do that in your future posts.
I certainly should have included an example with my post, sorry about that. I am currently running this under cygwin 2.3.1 but this will also run on openSuse 13.2 x86_64.

I know that the term csv is sometimes used to refer to generic delimited text data and not just comma separated data. I stay away from comma separation because many of the fields I use (chemical names) have commas ( 1,1,4,4-tetrabutylpiperazine ). The values in the name column could also have unmatched single quotes ( N,N,N',N'-tetramethylguanidine ) or parenthesis ( 1-(2-aminoethyl)piperazine ). I think that code that replaces space with comma would be problematic in my particular case. Yet another reason why an example of real data would have been useful for me to post.

LMHmedchem

Last edited by LMHmedchem; 11-25-2016 at 03:56 PM..
# 7  
Old 11-25-2016
This works if the name column is added to the headers file:
Code:
awk '
NR == FNR       {T[$1] = NR
                 next
                }
FNR == 1        {MX = NR - 1
                 for (i=1; i<=NF; i++) if ($i in T) C[T[$i]] = i
                }
                {for (j=1; j<=MX; j++) printf "%s%s", $C[j], (j == MX)?RS:"\t"
                }
' file2 file1
name	col_1	col_6	col_3	col_4	col_8	
name,1	2	0	1	0	9.6154	
name,2	7	0	0	0	8.6310	
name,3	4	0	1	0.6	4.6420	
name,4	6	0	1	0	7.7778	
name,5	2	0	3	0.833333	4.2924

This User Gave Thanks to RudiC For This Post:
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. UNIX for Beginners Questions & Answers

How to print multiple required columns dynamically in a file using the header name?

Hi All, i am trying to print required multiple columns dynamically from a fie. But i am able to print only one column at a time. i am new to shell script, please help me on this issue. i am using below script awk -v COLT=$1 ' NR==1 { for (i=1; i<=NF; i++) { ... (2 Replies)
Discussion started by: balu1234
2 Replies

2. Shell Programming and Scripting

Find header in a text file and prepend it to all lines until another header is found

I've been struggling with this one for quite a while and cannot seem to find a solution for this find/replace scenario. Perhaps I'm getting rusty. I have a file that contains a number of metrics (exactly 3 fields per line) from a few appliances that are collected in parallel. To identify the... (3 Replies)
Discussion started by: verdepollo
3 Replies

3. Emergency UNIX and Linux Support

Average columns based on header name

Hi Friends, I have files with columns like this. This sample input below is partial. Please check below for main file link. Each file will have only two rows. ... (8 Replies)
Discussion started by: jacobs.smith
8 Replies

4. Shell Programming and Scripting

Make copy of text file with columns removed (based on header)

Hello, I have some tab delimited text files with a three header rows. The headers look like, (sorry the tabs look so messy). index group Name input input input input input input input input input input input... (9 Replies)
Discussion started by: LMHmedchem
9 Replies

5. Shell Programming and Scripting

Compare two files and find match and print the header of the second file

Hi, I have two input files; file1 and file2. I compare them based on matched values in 1 column and print selected columns of the second file (file2). I got the result but the header was not printed. i want the header of file2 to be printed together with the result. Then i did below codes:- ... (3 Replies)
Discussion started by: redse171
3 Replies

6. Shell Programming and Scripting

awk based script to find the average of all the columns in a data file

Hi All, I need the modification for the below mentioned code (found in one more post https://www.unix.com/shell-programming-scripting/27161-script-generate-average-values.html) to find the average values for all the columns(but for a specific rows) and print the averages side by side. I have... (4 Replies)
Discussion started by: ks_reddy
4 Replies

7. Shell Programming and Scripting

Remove the file content based on the Header of the file

Hi All, I want to remove the content based on the header information . Please find the example below. File1.txt Name|Last|First|Location|DepId|Depname|DepLoc naga|rr|tion|hyd|1|wer|opr Nava|ra|tin|gen|2|wera|opra I have to search for the DepId and remove the data from the... (5 Replies)
Discussion started by: i150371485
5 Replies

8. Shell Programming and Scripting

Awk based script to find the median of all individual columns in a data file

Hi All, I have some data like below. Step1,Param1,Param2,Param3 1,2,3,4 2,3,4,5 2,4,5,6 3,0,1,2 3,0,0,0 3,2,1,3 ........ so on Where I need to find the median(arithmetic) of each column from Param1...to..Param3 for each set of Step1 values. (Sort each specific column, if the... (5 Replies)
Discussion started by: ks_reddy
5 Replies

9. Shell Programming and Scripting

Need to find a column from one file and print certain columns in second file

Hi, I need helping in finding some of the text in one file and some columns which have same column in file 1 EG cat file_1 aaaa bbbb cccc dddd eeee fffff gggg hhhh cat file_2 aaaa,abcd,effgh,ereref,name,age,sex,........... bbbb,efdfh,erere,afdafds,name,age,sex.............. (1 Reply)
Discussion started by: jpkumar10
1 Replies

10. UNIX for Dummies Questions & Answers

Changing file content based on file header

Hi, I have several text files each containing some data as shown below: File1.txt >DataHeader Data... Data... File2.txt >DataHeader Data... Data... etc. What I want is to change the 'DataHeader' based on the file name. So the output should look like: File1.txt >File1 ... (1 Reply)
Discussion started by: Fahmida
1 Replies
Login or Register to Ask a Question