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 am trying to extract lines from a file and save the output to a new file.

I have been using the code:

cat datafile | awk -f pullhh.txt > fuel

where the file pullhh.txt contains the code /FUELHH/

I want to extract lines containing the word FUELHH and save them to a file and then also extract lines containing FUELINST and save them to a separate file.

Is there a way to do this having both commands in the pullhh.txt file?

share|improve this question
    
You don't need a script file at all, just write awk '/FUELHH/ || /FUELINST/' datafile > fuel as glenn suggests –  terdon Jan 15 '13 at 15:18
    
@terdon: what about and save them to a separate file? –  sparkie Jan 16 '13 at 3:36
    
@sparkie, indeed, missed that, thanks, see my answer. –  terdon Jan 16 '13 at 11:57
add comment

3 Answers

Edit: to print to separate files:

/FUELHH/   {print > "fuelhh.txt"}
/FUELINST/ {print > "fuelinst.txt"}

Since "pullhh.txt" is actually an awk script, the "txt" extension is misleading. Use something like "extract_lines.awk" and then

awk -f extract_lines.awk datafile
share|improve this answer
    
diverting to 2 different files (as required by the thread opener) is not addressed by this solution –  sparkie Jan 16 '13 at 3:32
    
Thanks @sparkle, quite right. Answer edited. –  glenn jackman Jan 16 '13 at 3:50
add comment

since you want to divert the output to 2 different files I suggest the following (to execute via -f awk option).

BEGIN {
    while (getline line < "datafile" > 0) {
        if (match(line, "FUELHH"))   print line > "file1"
        if (match(line, "FUELINST")) print line > "file2"
    }
}

shorter solution:

{
    if (match($0, "FUELHH"))   print > "file1"
    if (match($0, "FUELINST")) print > "file2"
}
share|improve this answer
    
Why are you putting this in a BEGIN block? –  terdon Jan 16 '13 at 11:57
    
@terdon: because I'm so used to that:-) In larger scripts I often have to process many input files sequentially. The simple method isn't feasible there. Nevertheless I added a shorter solution - thanks for the pointer. –  sparkie Jan 16 '13 at 13:07
add comment

All you need is a one liner, no script file is necessary:

awk '/FUELHH/{print > "fuelhh.txt"}/FUELINST/{print}' datafile > fuelinst.txt
share|improve this answer
add comment

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.