Awk built-in variables and custom variables

In awk, variables are divided into two types: built-in variables and user-defined variables.

Today, let’s introduce the commonly used built-in variables and their use methods and the use methods of user-defined variables.

Common awk built-in variables:

  • FILENAME
    the name of the current input file.
  • FNR
    ordinal number of the current record in the current file.
  • FS
    regular expression used to separate fields; also settable by option -Ffs.
  • NF
    number of fields in the current record.
  • NR
    ordinal number of the current record.
  • OFS
    output field separator (default space).
  • ORS
    output record separator (default newline).

Examples of using built-in variables

  1. Use the NF variable to output the number of fields in the current record.
➜  ~ awk '{print NF}' test.log

2. Use the NF variable to output the value of the last field in the current record.

➜  ~ awk '{print $NF}' test.log

3. Use the NR variable to output the serial number of the current record.

➜  ~ awk '{print NR, $0}' test.log

4. Use the FILENAME variable to output the file name of the processing file.

➜  ~ awk '{print FILENAME, NR, $0}' test.log

➜  ~ awk '{print FILENAME, NR, NF}' test.log

5. Use FS variable to separate records.

➜  ~ awk 'BEGIN{FS=" "}{print $1}' test.log
➜  ~ awk -F" " '{print $1}' test.log

6. Use the OFS variable to output the record separator.

➜  ~ awk 'BEGIN{FS=" ";OFS="-"}{print $1,$2}' test.log

User defined variables

There are two types of user-defined variables.

1. Use -v parameter, -v varname = value variable names are case sensitive

➜  ~ awk -v my_variable="hello" 'BEGIN{print my_variable}'

2. Reference variables defined on the command line

➜  ~ echo $my_variable
➜  ~ my_variable="hello"
➜  ~ awk -v var=$my_variable 'BEGIN{print var}'

Add a Comment

Your email address will not be published.