Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
Hi All,
i have two text files (temp.txt and temp1.txt) like this
temp.txt has three columns
col11 col12 col13
temp1.txt has four columns
col21 col22 col23 col24 col25i want to get the all columns from temp.txt file and fetch the col24 and cold25 from temp1.txt file
expected output is:
col11 col12 col13 col24 col25How can i get the values using unix command?
Thanks in advance

There are probably any number of ways to do this. One way is two create a temp file with the required 2 columns then use the paste command to glue the files together:
awk ' { printf ("%s %s", $4, $5) } ' temp1.txt > ./mytemp
paste -d " " temp.txt ./mytemp

ghostdog: would you mind breaking down that awk for me? my knowledge of awk is pretty limited and your example is interesting and potentially very useful; i'd love to understand the working behind it.

i would love to explain to you, but i am not good at explaining. pls look at the manual . it explains what is FNR and NR as well as the basics you will need.

ghostdog that's a neat trick. I'll take a shot at explaining it:
awk 'FNR==NR{_[++d]=$0;next}{print _[FNR],$4,$5}' file1 file2
First, two definitions:
FNR is the input record number of the current input file
NR is the total number of input records read, so far,regardless of the number of input files.The awk one-liner can be split into 2 pieces. The first piece builds the array _[] from the first file, file1, The array is built because FNR always equals NR while file1 is read. The next statement gets the next line of file1 preventing the script from continuing until the file1 is read.
Each line of file1 is set to an element of the array indexed by d. The index increases by 1 after the line, $0, is assigned to the array element.
The second part of the script involves printing out each element of the array and fields 4 and 5 of file2. When the second input file2, becomes the input file, the FNR variable resets to 0. Now, with FNR being the index into thte array, it is insync with each line read from file2.
I don't know if I did a good job of explaining so here is another variation that might be easier to understand:
# using nawk for Solaris nawk ' BEGIN { d=0; while(getline < "temp.txt" > 0) _[++d]=$0 } { print _[NR],$4,$5 } ' temp1.txtIn the above scirpt, file1 is read and the array is built in the BEGIN section. Then, the main section reads file2, and each record number of file2, NR, is used as the index into the array.
.

![]() |
![]() |
![]() |
| Login or Register to Reply | |
| Login | Register |
| Ads by Google |