Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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?

share|improve this question
1  
Please provide some example input and expected output. –  Thor Jan 28 '13 at 14:45

2 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
share|improve this answer
    
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 Jan 28 '13 at 14:08
    
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 Jan 28 '13 at 14:30
    
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 Jan 28 '13 at 16:26
    
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 Jan 28 '13 at 16:52
    
The substr is a good idea, +1. I edited your answer to print only the 4 characters after the FG=. –  terdon Jan 28 '13 at 17:35

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
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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