Linux awk Command Examples
===========================
awk '{print $2, $3}' my.txt
print 2nd & 3rd fields separated by space
awk '{print $2 "," $3}' my.txt
print 2nd & 3rd field separated by comma
awk '/error/' my.txt
print lines containing the text "error"
awk '{sum=$1+$2; print sum}' my.txt
sum up 1st and 2nd fields of each line
awk '{print NR, $0}' my.txt
add line number to each line and print it
awk '{print NF}' my.txt
print the number of fields in each line
awk '{print $1, $NF}' my.txt
print 1st and last fields
awk 'NR>1 {print}' my.txt
skip the header line
awk '$2 >100' my.txt
print lines where 2nd field is > 100
awk 'NF>0' my.txt
remove empty or whitespace-only lines
awk '$1 == 100' my.txt
print lines where 1st field equals to 100
awk '{s+=$2; c++} END {print s/c}' my.txt
compute average of 2nd field
awk '$1>100 {s+=$2; c++} END {print s/c}' my.txt
average with condition
awk '{print toupper($2)}' my.txt
print 2nd field in uppercase
awk '$1=="ERR" {print $2}' my.txt
print 2nd field if 1st field is "ERR"
awk '{print "Name:", $1, "Age:", $2}' my.txt
formatted printing
awk -F',' '{print $2, $3}' my.csv
use comma "," as the field separator
awk '{print substr($2,1,3)}' my.txt
extract substring from 2nd field
awk 'function sq(x) {return x*x} {print sq($2)}' my.txt
define a function
awk '!seen[$1]++' my.txt
remove duplicate lines based on 1st column
awk 'length($2) > 3' my.txt
print lines where length of 2nd field is > 3
awk '{gsub(/old/,"new"); print}' my.txt
replace every "old" with "new"
awk '$1 ~ /ERR/' my.log
print lines where 1st field matches pattern
awk '$1 !~ /ERR/' my.log
print lines where 1st field doesn't match pattern
awk '$1 ~ /^[0-9]+$/' my.log
print lines where 1st field has only digits
awk '{$1=$1; print}' my.txt
trim whitespace and collapse internal spaces
---
No comments:
Post a Comment