Is it possible to combine bash and awk script files?

I have a bash script where I get the values ​​of a variable that I would like to use in awk. Is it possible to include all awk in it (for example, with bash script files) in bash for example:

#!/bin/sh var1=$1 source myawk.sh 

and myawk.sh:

 print $1; 
+2
source share
4 answers

First of all, if you write bash, do not use #!/bin/sh , which puts you in compatibility mode, which is only necessary if you write for portability (and then you must adhere to the POSIX normative).

Now, regarding your question, you just need to run awk from your bash script, for example:

 #!/bin/bash var1=$1 awk -f myawk.sh 

you should also use .awk as an extension, I think.

+2
source

Bash and awk are different languages, each with its own interpreter of the same name. The small sample you show is tidy up too much to make sense:

  • You marked both files as shell scripts; one uses shebang #!/bin/sh and the other uses the .sh extension. Obviously, the shell can read the shell script, and the command for this is called . in the Bourne shell (or source in csh and bash).
  • The shell script assigns a variable, but you don't use it anywhere. Did you mean switching to awk script?
  • Both awk and shell script use $ 1, which has different values ​​for them (in bash, it is from the command line or set command, in awk, from the parsed line).

Two tools are often used in tandem, because the shell better combines separate programs, and awk better reformats table or structured text. It was so often that a whole language developed to integrate tasks; Perl's roots are a combination of shell, awk, and sed.

If you just want to pass a variable from a shell script to an awk script, use -v. User page is your friend.

+4
source

Or, many ppl do it like this:

 #!/bin/env bash #Bash things start ... var1=$1 #Bash things stop #Awk things start, #may use pipes or variable to interact with bash awk -v V1=var1 ' #AWK program, can even include awk scripts here. ' #Bash things 

I suggest this page here by Bruce Barnett:

http://www.grymoire.com/Unix/Awk.html#uh-3

You can also use a double quote to use the shell retrieval function, but this is confusing.

Personally, I just try to avoid these fancy gnu additions from bash or awk and make my ksh + (n) awk scripts compatible.

+1
source

As an AWK hardcore user, I soon realized that doing the following was really a huge help:

  • Defining and exporting AWK_REPO variable in my bashrc
    #Content of bashrc
    export AWK_REPO=~/bin/AWK
  • Saving every AWK script there, I write using the .awk extension.
  • Then you can call it from anywhere: awk -f $AWK_REPO/myScript.awk $file
    or even using Shebangs and adding AWK_REPO to PATH (with export PATH=${AWK_REPO}:${PATH} )
    myScript.awk $file
+1
source

Source: https://habr.com/ru/post/1387029/


All Articles