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?

  • 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
  • diverting to 2 different files (as required by the thread opener) is not addressed by this solution – sparkie Jan 16 '13 at 3:32

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"
  • 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

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.