In Linux, awk
is a powerful text processing tool that can be used to match strings and output them. Here are some basic awk
command examples for matching strings and outputting related lines or parts of content:
- Match a specific string and output the whole line:
awk '/string_to_match/' filename
This will output all lines containing “string_to_match”.
- Match a string and output part of the line:
awk '$1 == "field1" {print $2}' filename
This will output the second column of the lines where the first column (field) is “field1”.
- Use regular expressions to match a string:
awk '/regular_expression/' filename
For example, if you want to match lines starting with “start”, you can use:
awk '/^start/' filename
- Match lines that do not contain a specific string:
awk '!/string_to_exclude/' filename
This will output all lines that do not contain “string_to_exclude”.
- Match multiple conditions:
awk 'condition1 && condition2 {print $1}' filename
For example, to match lines where the first column is “field1” and the second column is “field2”:
awk '$1 == "field1" && $2 == "field2" {print $1}' filename
- Use variables and pattern matching:
awk -v pattern="string_to_match" '$0 ~ pattern' filename
This will output all lines containing “string_to_match”.
- Output a specific column of the matching line:
awk -F":" '/string_to_match/ {print $1}' filename
This sets the field separator to “:” and outputs the first field of the matching line.
- Output the line number of the matching line:
awk '/string_to_match/ {print NR}' filename
This will output the line numbers of the lines containing “string_to_match”.
- Use multiple pattern matches:
awk '/pattern1/,/pattern2/' filename
This will output all lines from the first pattern match to the second pattern match.
- Use
if
statements for more complex conditional judgments:bash awk '{if (condition) print $0}' filename
These are just some basic uses of awk
. The functionality of awk
is very powerful, and more complex scripts can be written according to needs.