Certainly! Here are some common awk examples that demonstrate its versatility in text processing:
-
Print Specific Columns:
awk '{print $1, $3}' file.txtThis command prints the first and third columns of each line in
file.txt. -
Using a Delimiter:
awk -F',' '{print $1, $2}' file.csvThis command uses a comma as a delimiter and prints the first and second columns from a CSV file.
-
Conditional Printing:
awk '$3 > 50 {print $1, $3}' file.txtThis command prints the first and third columns of lines where the value in the third column is greater than 50.
-
Counting Lines:
awk 'END {print NR}' file.txtThis command counts the total number of lines in
file.txtand prints the count. -
Calculating the Sum of a Column:
awk '{sum += $2} END {print sum}' file.txtThis command calculates the sum of the values in the second column and prints the result.
-
Finding the Average of a Column:
awk '{sum += $2; count++} END {print sum/count}' file.txtThis command calculates the average of the values in the second column.
-
Formatting Output:
awk '{printf "Name: %s, Age: %d\n", $1, $2}' file.txtThis command formats the output to display names and ages in a specific format.
-
Replacing Text:
awk '{gsub(/old_text/, "new_text"); print}' file.txtThis command replaces all occurrences of "old_text" with "new_text" in
file.txtand prints the modified lines.
These examples illustrate how awk can be used for a variety of text processing tasks, making it a powerful tool for data manipulation in the command line.
