Can you give more `awk` examples?

076

Certainly! Here are some common awk examples that demonstrate its versatility in text processing:

  1. Print Specific Columns:

    awk '{print $1, $3}' file.txt

    This command prints the first and third columns of each line in file.txt.

  2. Using a Delimiter:

    awk -F',' '{print $1, $2}' file.csv

    This command uses a comma as a delimiter and prints the first and second columns from a CSV file.

  3. Conditional Printing:

    awk '$3 > 50 {print $1, $3}' file.txt

    This command prints the first and third columns of lines where the value in the third column is greater than 50.

  4. Counting Lines:

    awk 'END {print NR}' file.txt

    This command counts the total number of lines in file.txt and prints the count.

  5. Calculating the Sum of a Column:

    awk '{sum += $2} END {print sum}' file.txt

    This command calculates the sum of the values in the second column and prints the result.

  6. Finding the Average of a Column:

    awk '{sum += $2; count++} END {print sum/count}' file.txt

    This command calculates the average of the values in the second column.

  7. Formatting Output:

    awk '{printf "Name: %s, Age: %d\n", $1, $2}' file.txt

    This command formats the output to display names and ages in a specific format.

  8. Replacing Text:

    awk '{gsub(/old_text/, "new_text"); print}' file.txt

    This command replaces all occurrences of "old_text" with "new_text" in file.txt and 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.

0 Comments

no data
Be the first to share your comment!