LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - General (https://www.linuxquestions.org/questions/linux-general-1/)
-   -   Awk (https://www.linuxquestions.org/questions/linux-general-1/awk-585260/)

opensource82 09-17-2007 07:24 AM

Awk
 
Hi all,
I have a question about awk. I need to put a field in a file to another field in another line. for example let us say that file1 contain the following:

A B C

and file 2 :

E F G

I want to take field number 2 "$2" from file1 which is (B) to put it as field number 4 "$4" in file 2. How can i do that.

Regards,

colucix 09-17-2007 08:25 AM

If you want to do this from command line, without a more complex GAWK script, you can use a for loop to extract $2 from each line of file1 and append the value at the end of the corresponding line in file2, as in
Code:

count=0
for item in `gawk '{print $2}' file1`
> do
> count=$((count + 1))
> gawk -v var=$item -v num=$count '{if ( NR == num ) print $0, var}' file2
> done

However, the dis-advantage of this approach is the great number of calls to gawk, if file1 has a huge number of lines.

opensource82 09-17-2007 09:12 AM

So is there is another way to do that without awk?

colucix 09-17-2007 09:58 AM

Actually I was thinking about an awk script to send output to an external file, anyway here is a one line command which do the same thing
Code:

gawk '{print $2}' file1 | paste -d \  file2 -
this uses the command paste which comes with coreutils. Please note the double space after -d \ . This tells to use a blank space (escaped) as delimiter, instead of the default tab. See man paste for details.

opensource82 09-18-2007 06:23 AM

Thanks for the new command but we still didn't detremine the field in the second file. any idea?

colucix 09-19-2007 09:08 AM

Do you mean to insert a column from file1 as any column in file2? Assuming that the two files have the same number of columns and there are no blank elements, you can try something like
Code:

{ getline line < ifile
  split(line,array)
  for (i = 1; i <= ocol - 1; i++)
      printf("%s ", $i)
  printf("%s ", array[icol])
  for (i = ocol; i <= NF; i++)
      printf("%s ", $i)
  printf("\n")
}

where icol is the column to read from file1 (that is the second field to extract, in your example), ocol is the column to insert in file2 and ifile is the input file (file1). If you put the above code in a file, e.g script.awk, you can launch it as
Code:

gawk -v icol=2 -v ocol=2 -v ifile=file1 -f script.awk file2
You can play with this code adding some controls. For details about the usage of the getline statement in gawk, the reference is the Gawk: Effective AWK Programming guide, section 3.8.4. Bye


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