LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (http://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   awk question (http://www.linuxquestions.org/questions/linux-newbie-8/awk-question-331224/)

denalitastic 06-07-2005 10:49 AM

awk question
 
Hello I am trying to use awk to do this.

I have two files lets say file1.txt and file2.txt. file1.txt has 1 column. And file2.txt has 3 columns. I want to insert the column from file1.txt into file2.txt as the new column 3 or for that matter any column. But lets stick to the first case, So then I would have a 4 column file2.txt that would look like

file2colum1 file2colum1 file1colum1 file2colum3.

How do I do this, is there a command for that? I dont want any matching etc like the join command uses. I just want to insert the column.

-denalitastic

druuna 06-07-2005 11:42 AM

Hi,

Using awk:

Code:

#!/bin/bash

awk  '
  BEGIN {
          # load array with contens f1.txt
          while ( getline < "f1.txt" > 0 )
            {
              f1_counter++
              f1[f1_counter] = $1
            }
  }
  {
    print $1, $2, f1[NR], $3
  } ' f2.txt

In the BEGIN part all content of f1.txt is loaded into an array. The correct array entry can be printed by using the NR variable that holds the current record value. So print $1, $2, f1[NR], $3 first prints fields 1 and 2 from f2.txt, then f1[NR], which is the corresponding entry from f1.txt. Last the third field from f2.txt is printed.


cat f1.txt
F1column1
F1column1
F1column1
F1column1
F1column1

cat f2.txt
f2column1 f2column2 f2column3
f2column1 f2column2 f2column3
f2column1 f2column2 f2column3
f2column1 f2column2 f2column3
f2column1 f2column2 f2column3

Output above script:

f2column1 f2column2 F1column1 f2column3
f2column1 f2column2 F1column1 f2column3
f2column1 f2column2 F1column1 f2column3
f2column1 f2column2 F1column1 f2column3
f2column1 f2column2 F1column1 f2column3

Hope this helps.


All times are GMT -5. The time now is 10:31 AM.