Skip to content

Instantly share code, notes, and snippets.

@renatocassino
Last active January 18, 2017 12:56
Show Gist options
  • Save renatocassino/62fe9f6e6909866e5d2e8cd8e5ccf0c8 to your computer and use it in GitHub Desktop.
Save renatocassino/62fe9f6e6909866e5d2e8cd8e5ccf0c8 to your computer and use it in GitHub Desktop.
# 3697
# Syntax
awk '/pattern/ { commands }' textfile
## System variables
# FS = Field Separator (Define the separator for variables)
# NF = Number Fields (Number of fields getted by a field separator)
# RS = Record Separator (Record separator is a new line by default "\n")
# FILENAME = The name of the file that awk is reading
# BEGIN = Run command and change vars before the script
# END = Run command after script
awk 'BEGIN { FS=" "; print "START" } { print $1 } END {print NR " lines processed" }' filename
# Response
START
firstword
first
word
3 lines processed
# Count blank lines in a file
awk '/^$/ { lines += 1 } END { print lines " in this file" }' comma
# Response
3 lines in this file
# Media for students
cat students
Robert Kliebert 7 7.5 8.1 9
Louise Love 9.2 7.4 8.2 10
Carol Tiedemann 10 7.6 8.4 9.1
Thomas Lambeth 4.3 4.5 6.1 5.2
Darren Sims 5.4 7.5 7.4 7
awk '{ 1 ↵
total = $3 + $4 + $5 + $6
avg = total / 4
print $1 " " $2 ", " avg
} ' students
# Response
Robert Kliebert, 7.9
Louise Love, 8.7
Carol Tiedemann, 8.775
Thomas Lambeth, 5.025
Darren Sims, 6.825
# Media with media class media
awk '{
total_of_students += 1
total = $3 + $4 + $5 + $6
avg = total / 4
avg_total += avg
print $1 " " $2 ", " avg
} END {
avg_all = avg_total / total_of_students
print "Total avg: " avg_all
}' students
# Response
RobertKliebert, 7.9
LouiseLove, 8.7
CarolTiedemann, 8.775
ThomasLambeth, 5.025
DarrenSims, 6.825
Total avg: 7.445
# Balance the checkbook
cat market
1000
125 market -125.45
126 Hardware Store -34.95
127 Video Store -7.45
128 Book Store -14.32
129 Gasoline -16.10
# PS: To print a tab in terminal, press CTRL+V tab
# Create checkbook.awk with this content
# Separating by tab
BEGIN { FS = "\t" }
# Expect the first record to have the starting balance
NR == 1 { print "Beginnig Balance: \t" $1
balance = $1
next
}
{
print $1, $2, $3
print balance += $3
}
END {
print "New balance is: " balance
}
awk -f checkbook.awk market
Beginnig Balance: 1000
125 market -125.45
874.55
126 Hardware Store -34.95
839.6
127 Video Store -7.45
832.15
128 Book Store -14.32
817.83
129 Gasoline -16.10
801.73
New balance is: 801.73
# Print with a better format
# You can use printf in yout checkbook.awk
BEGIN { FS = "\t" }
# Expect the first record to have the starting balance
NR == 1 { print "Beginnig Balance: \t" $1
balance = $1
next
}
{
printf "%10-s\t%10-s\t%10s\n", $1, $2, $3 # You must put the \n with printf
print balance += $3
}
END {
print "New balance is: " balance
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment