Forrest logo
back to the awk tool

awk:tldr:16f09

awk: Print different values based on conditions.
$ awk '{if ($1 == "foo") print "Exact match foo"; else if ($1 ~ "bar") print "Partial match bar"; else print "Baz"}' ${filename}
try on your machine

This command is using the awk programming language to perform text processing on the contents of a file specified by ${filename}.

Here is a breakdown of the command:

  • awk: This is the command used to invoke the awk programming language interpreter.

  • '{}': These curly braces contain the awk script or program that will be executed.

  • if ($1 == "foo") print "Exact match foo";: This checks if the first field ($1) of each line in the file is equal to the string "foo". If it is, it prints the string "Exact match foo".

  • else if ($1 ~ "bar") print "Partial match bar";: If the first condition is not satisfied, this checks if the first field of the line matches the pattern "bar". The ~ symbol is the pattern matching operator in awk. If there is a partial match, it prints the string "Partial match bar".

  • `else print "Baz"': If neither of the previous conditions is satisfied, this prints the string "Baz".

  • ${filename}: This is the variable that holds the filename or path of the file on which the awk script will be executed.

This explanation was created by an AI. In most cases those are correct. But please always be careful and never run a command you are not sure if it is safe.
back to the awk tool