Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

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

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

    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

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .