Skip to content

Instantly share code, notes, and snippets.

@bsnux
Last active April 6, 2021 04:30
Show Gist options
  • Save bsnux/3f5e6152101a46386f95780c91a680c7 to your computer and use it in GitHub Desktop.
Save bsnux/3f5e6152101a46386f95780c91a680c7 to your computer and use it in GitHub Desktop.
#!/bin/bash
# Print only lines matching expression
awk -F: '/ssh/ { print } ' /etc/group
# Print only if field 4 matchs expression
awk -F: 'match($4,/ssh/) { print } ' /etc/group
# Print field 1 only if field 4 matchs expression
awk -F: 'match($4,/ssh/) { print $1 } ' /etc/group
# Print text before printing all file
awk 'BEGIN {print "The File Contents:"} {print $0}' /etc/group
# Print footer
awk 'BEGIN {} {print $0} END {print "File footer"}' /etc/group
# Print sum of numbers
awk '{sum += $1} END {print sum}' test.txt
# Print number of lines in file
awk 'END { print NR }' /etc/group
# Replace only first instance in line
awk '{sub(/HTML/, "html")}; 1' data.txt > data_new.txt
# Replace all instances in line
awk '{gsub(/HTML/, "html")}; 1' data.txt > data_new.txt
# Replace all instances of "foo" with "bar"
awk '{gsub(/foo/,"bar");print}'
# Swap first two columns of every line
awk '{temp=$1; $1=$2; $2=temp} 1' data.txt
# Delete second column from every line
awk '{ $2 = ""; print }' data.txt
# Print all except lines containing pattern
awk '!/ssh/ {print }' /etc/group
# Print all except lines containing pattern starting in line 5
awk '! /ssh/ { if (NR>4) print}' /etc/group
# Print last field
awk '{ print $NF }' /etc/group
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment