extracting words using awk

0

I have a data file that is made up of lines that all contain FG=???? (where ???? represents a four digit number that is different on each line ).

I would like to extract this from each line and save it to a new file. Is this possible to do using awk?

I have been using the /this/ to extract lines containing the word this. Is there something similar for extracting a word from a line?

Jennifer

Posted 2013-01-28T13:33:52.087

Reputation: 1

1Please provide some example input and expected output. – Thor – 2013-01-28T14:45:27.763

Answers

2

You can select a range of characters from each line:

awk '{print substr($0,4,4)}' file.txt

Specifically for your case:

awk -F 'FG=' '{print substr($2,0,4)}' file.txt

You can also use cut:

cut -b4-7 file.txt

cYrus

Posted 2013-01-28T13:33:52.087

Reputation: 18 102

I tried this but there isn't a space before the FG so it extracts the whole thing. Sorry I didn't realise this before. So is there a way of extracting part of the word? – Jennifer – 2013-01-28T14:08:22.393

And indeed I didn't use a space in my example, what makes you think that this solution requires a space? Since you tagged your question unix I can think about some differences with the Linux version (that I'm using). – cYrus – 2013-01-28T14:30:58.863

This won't work unless the fileds are actually separated by =. Otherwise, awk will take as $2 everything after the first =. That is why it is printing the entire line. – terdon – 2013-01-28T16:26:02.610

I'm assuming that each line is in the form: /^FG=[0-9]{4}$/. The OP doesn't state it explicitly. Anyway I'll update my answer to reflect that case too. – cYrus – 2013-01-28T16:52:52.803

The substr is a good idea, +1. I edited your answer to print only the 4 characters after the FG=. – terdon – 2013-01-28T17:35:03.140

0

I could give you a pure awk answer if you post an example of your actual data. In the absence of specific clues, you can always try Perl:

perl -ne '/FG=(\d+)/; print "$1\n"'  infile.txt > outfile.txt

terdon

Posted 2013-01-28T13:33:52.087

Reputation: 45 216