LinuxQuestions.org

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

groys 05-25-2009 01:59 AM

awk question
 
Hi,
I have multiple files with data arranged in columns. I am trying to read create an new file, which will have the 1st column and 5th column from the 1st file and the 5th column from all the other files. Reading some other posts i wrote a poor script like this

#! /bin/bash
pr -m -t -s\ file1 file2 file3 file4 file5 file6 file7 | gawk '{print $1,$5,$12,$19,$26,$33,$40,$47,$54}'

How can I generalize this so that I don't have to hardcode these things? Is there anyway I can read each file in a folder and generate one output file which has the 5th column of each of the files?

Thanks
Gautam

colucix 05-25-2009 02:16 AM

Awk can process multiple files together. If you want to extract the 1st and 5th field from one particular file, you can check the awk variable FILENAME:
Code:

awk '{if ( FILENAME == "file1" ) print $1,$5; else print $5}' file1 file2 file3

sycamorex 05-25-2009 02:17 AM

To read each file in a directory you need a 'for' loop:
Code:

for file in *
  do
  # do_something_with_the $file, for example:
  awk -F: '{ print $5} $file >> newfile
  done

It will go through each file in the current directory and append the fifth column to a new file 'newfile'
Is that what you mean?

groys 05-25-2009 04:29 AM

thanks a lot, colunix and sycomorex...this is what i was trying to do.
:)


All times are GMT -5. The time now is 07:20 PM.