Executing multiple awk commands in one file

0

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?

Jennifer

Posted 2013-01-15T14:31:56.813

Reputation: 1

You don't need a script file at all, just write awk '/FUELHH/ || /FUELINST/' datafile > fuel as glenn suggests – terdon – 2013-01-15T15:18:08.543

@terdon: what about and save them to a separate file? – sparkie – 2013-01-16T03:36:37.517

@sparkie, indeed, missed that, thanks, see my answer. – terdon – 2013-01-16T11:57:23.243

Answers

4

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

glenn jackman

Posted 2013-01-15T14:31:56.813

Reputation: 18 546

diverting to 2 different files (as required by the thread opener) is not addressed by this solution – sparkie – 2013-01-16T03:32:57.007

1

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

sparkie

Posted 2013-01-15T14:31:56.813

Reputation: 2 110

Why are you putting this in a BEGIN block? – terdon – 2013-01-16T11:57:42.977

@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 – 2013-01-16T13:07:58.170

0

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

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

terdon

Posted 2013-01-15T14:31:56.813

Reputation: 45 216