Last Updated : 01 Nov, 2024
The gawk command in Linux is a pattern scanning and processing language. No compilation is required, and variables can be used along with numeric functions, string functions, and logical operators.
Gawk is a utility that enables programmers to write highly compact but still effective programs as statements that define text patterns to look for in a text document, and the action to be taken every time such a match is found within a line.
Gawk can be used to:gawk [POSIX / GNU style options] -f progfile [--] file ...Basic gawk Command Example
gawk [POSIX / GNU style options] [--] 'program' file ...
By default, gawk prints every line of data from the named file:
gawk '{ print }' mobile.txtTerminal output of the gawk command printing all lines from the mobile.txt Basic Options and Usage
Option
Description
-f progfile, --file=progfile
Read the AWK program source from the file program-file, instead of from the first command line argument
-F fs, --field-separator=fs
Use FS for the input field separator (the value of the FS predefined variable)
-v var=val, --assign=var=val
Assign the value val to the variable var, before execution of the program begins
Examples of Option UsageSpecifying field separator using -F option:
gawk -F: '{ print $1 }' /etc/passwdTerminal output of gawk command with -F option
Using -f option to read program from a file:
gawk -F: -f mobile.txt /etc/passwdBuilt-In Variables
Example using NR:
gawk '{ print NR "-" $1 }' mobile.txtTerminal output of gawk command using NR variable Advanced Usage Examples
Assume that we have a dataset in a file named mobile.txt:
Name Mobile Email
John 1234567890 john@example.com
Sunil 9876543210 sunil@example.com
Alice 5555555555 alice@example.com
1. Print lines matching a pattern:
gawk '/Sunil/ ' mobile.txtoutput
2. Print specific fields:
gawk '{ print $2 }' mobile.txtoutput
3. Count the number of lines in a file:
gawk 'END NR}' mobile.txtoutput Conclusion
The gawk command is actually one of the most powerful tools in Linux when it comes to text processing. The tool can scan files, process patterns, and execute many actions; it is very valuable to both system administrators and programmers. Mastering gawk will allow users to easily manipulate text data, generate reports, or automatically automate many other text-processing activities.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4