jax
jax

Reputation: 747

Awk from a file

How do I use awk in a bash file?

I know how to do this on the command line with

awk `{...}`

But how do I do place this in a bash file.

This is what I'm doing right now

awk

Begin
{

    ...
}
{
    ...
}
END
{
   ...
}

What am I missing from the syntax?

Upvotes: 0

Views: 388

Answers (2)

TrueY
TrueY

Reputation: 7610

If the script is complicated then you may create an script file and add run rights to it. Using fedorqui's example the x.awk file could be like this:

#!/bin/awk -f

BEGIN {print "-entering in awk script"}
{print $1, $3}
END {print "-that was it"}

Then chmod 700 x.awk and then one can use x.awk as a normal utility:

#!/bin/bash
./x.awk input_file.txt

Upvotes: 1

fedorqui
fedorqui

Reputation: 289725

Just add it normally, such like this:

awk '...' file

Note that, instead, you were using

awk `{ ... }` file

Also note BEGIN and END blocks need the opening brace to be in the same line. Otherwise you will get an error like this:

awk: cmd. line:2: BEGIN blocks must have an action part

Use BEGIN, not Begin.


See a complete working example:

$ cat a
#!/bin/bash

echo "we received file: $1"

awk 'BEGIN {print "-entering in awk script"}
     {print $1, $3}
     END {print "-that was it"}' $1

And this is the file we will provide:

$ cat b
hello this is a test
and this another text

And we execute it:

$ ./a b
we received file: b
-entering in awk script
hello is
and another
-that was it

Upvotes: 3

Related Questions