bash-tutorial/tutorial/gawk.org

3.1 KiB
Raw Blame History

Using gawk in command-line

gawk stands for GNU-awk

awk is a data driven program that search text in files using a pattern. After finding the pattern awk performs operations on these files. awk is not bash, but since you can use it from a shell, let's talk about awk in this tutorial.

Syntaxis

Use the following and apply to files or to standard input ('INPUT')

  awk PATTERN { ACTION } INPUT

awk can be run directly in the command-line, or you can write scripts and run them.

  set +H #disabling c-shell-style to avoid treat '!' as special character
compartido@compartido: ~/Documentos/GNU/bash/bash-tutorial
compartido@compartido: ~/Documentos/GNU/bash/bash-tutorial
  awk 'BEGIN { print " Don\47t Panic!" }'
Don't Panic!

To run the program from a file, use the 'f' argument followed by the name of the file.

   awk -f file.awk
Dont Panic!

awk scripts use the following before the code

#! /bin/awk -f

Then, make the file executable ('chmod +x file.awk')

Data

Check in awklib/eg/data

  awk '/li/ { print $0}' mail-listc
Amelia   555-5553 amelia.zodiacusque@gmail.comF
 Broderick555-0542 broderick.aliquotiens@yahoo.com R
 Julie555-6699 julie.perscrutabor@skeeve.com   F
 Samuel   555-3430 samuel.lanceolis@shu.eduA
compartido@compartido: ~/Documentos/GNU/bash/bash-tutorial

Printing is the default action. Thus, when printing is omitted, awk as action in the code, the output will still be printed.

  awk 'length($0) > 50' mail-listc
Anthony  555-3412 anthony.asserturo@hotmail.com   A
 Broderick555-0542 broderick.aliquotiens@yahoo.com R
compartido@compartido: ~/Documentos/GNU/bash/bash-tutorial

awk examples

Compare two text files

$ awk ' NR==FNR { # process b.txt or the first file seen[$0] # hash words to hash seen next # next word in b.txt } # process a.txt or all files after the first !($0 in seen)' b.txt a.txt # if word is not hashed to seen, output it

awk ' NR==FNR { seen[$0] next } !($0 in seen)' diagnostico_es_2022-03-21.org ../reunion/reunion_2022_03_20.org

git diff diagnostico_es_2022-03-21.org ../reunion/reunion_2022_03_20.org

References

  • awk info manual