1

I would like to extract two values from a series of .txt files.

This is the last two lines (line 49 & line 50) of my .txt file

1  13593 3434 2.2585  0.9
2   3333  333 3.7118  0.8

& I want to extract the 4th column (ex. 2.2585 & 3.7118) of line 49 and line 50 from each .txt file.

Is there a way to do it?

Thanks so much

  • 2
    Are the values always in 4th column? And you want the 4th column value of only 49th and 50th lines of each .txt file or all values at 4th column of each .txt files? – trishnendu Nov 1 '16 at 18:56
  • Please edit and clarify your question; do you always want to extract the values from the last two lines of each file? – maulinglawns Nov 1 '16 at 19:01
  • Yes, the values are always in the 4th column, and I want the 4th column of only 49th and 50th line of each text file. – jahanvi patel Nov 1 '16 at 19:01
2

You can use awk for text processing. The following awk statement reads the file 'input' and prints the value at column 4 of line 49 and 50.

awk 'FNR==49 || FNR==50 {print $4}' input

Now to read all the files in the directory (assuming all files are in same directory) you can run a for loop to read filenames. So the final statement will be like -

for file in *; do awk 'FNR==49 || FNR==50 {print $4}' "$file"; done

And as trosos mentioned, the inputs files are only .txt format. So we can do

awk 'FNR==49 || FNR==50 {print $4}' *.txt

  • You can avoid the for and just do awk 'FNR>48{print $4}' *.txt – trosos Nov 1 '16 at 19:29
  • Oh! yes. She has specified ".txt" format of the files. Thanks, I am modifying my answer. – trishnendu Nov 1 '16 at 19:31
  • Thanks trishnendu, maulinglawns & trosos. It worked nicely ! – jahanvi patel Nov 2 '16 at 14:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.