Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
676 views
in Technique[技术] by (71.8m points)

awk extract a column and output a file named by the column header

I have a .txt file like this:

col1    col2    col3    col4
1   3   4   A
2   4   6   B
3   1   5   D
5   3   7   F

I want to extract every single column (i) after column 1 and output column1 and column i into a new file named by the header of column i.

That means that I will have three output files named "col2.reform.txt", "col3.reform.txt" and "col4.reform.txt" respectively.

For example, the output "col2.reform.txt" file will look like this:

col1    col2
1   3
2   4
3   1
5   3

I tried my code like this:

awk '{for (i=1; i <=NF; i++) print $1""$i > ("{awk 'NR==1' $i}"".reform.txt")}' inputfile

And apparently the "{awk 'NR==1' $i}" part does not work, and I got a file named {awk 'NR==1' $i}.reform.txt.

How can I get the file name correctly? Thanks!

PS: how can I deleted the file "{awk 'NR==1' $i}.reform.txt" in the terminal?

Edited: The above column name is just an example. I would prefer to use commands that extract the header of the column name, as my file in reality uses different words as the header.

question from:https://stackoverflow.com/questions/65941781/awk-extract-a-column-and-output-a-file-named-by-the-column-header

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

here's a similar one...

$ awk 'NR==1 {n=split($0,h)} 
             {for(i=2;i<=n;i++) print $1,$i > (h[i]".reform.txt")}' file

==> col2.reform.txt <==
col1 col2
1 3
2 4
3 1
5 3

==> col3.reform.txt <==
col1 col3
1 4
2 6
3 5
5 7

==> col4.reform.txt <==
col1 col4
1 A
2 B
3 D
5 F

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...