Skip to content

Instantly share code, notes, and snippets.

@cyb3rsalih
Last active August 1, 2020 16:15
Show Gist options
  • Select an option

  • Save cyb3rsalih/26cda529a84db88ce9e48d41a68842d2 to your computer and use it in GitHub Desktop.

Select an option

Save cyb3rsalih/26cda529a84db88ce9e48d41a68842d2 to your computer and use it in GitHub Desktop.
AWK Cheatsheet
file.txt is something like this. ls with size of files
"""
asd 12213
asd 1231231
sdas 4534
sdas 4534
sdas 4534
sdas 4534
sdas 4534
"""
awk '{print $0}' file.txt -> Prints whole lines of file
awk '{print $1}' file.txt -> Prints 1st element of each line of file
awk '{print $2}' file.txt -> Prints 2nd element of each line of file
awk '{print $1,$2}' file.txt -> Prints 1st and 2nd element of each lines of file
awk '/gcc/ {print $1}' file.txt -> Prints 1st element of each lines of file which contains regex /gcc/
awk '{print $1,$2/1024"K"}' file.txt -> Prints 1st element of each line and divide 2nd element of each line to 1024 and add K char
awk '/gcc/ && $2 > 15 {print $1}' file.txt -> Prints if 1st element of each lines of file which
contains regex /gcc/ and the 2nd element of each line is greater than 15
echo "/gcc/ && $2 > 15 {print $1}" >> script.awk
awk -f script.awk file.txt
awk '{print $1,int($2/1024)"K"}' file.txt -> cast the 2nd line to integer
Use functions in awk scripts
"""
func round(n){
n = n + 0.5
n = int(n)
return n
}
/gcc/ && $2 > 15 {print $1,round($2/1024)"K"}
"""
func printlist(n){
for(i=1;i<=n;i++){
printf("%d",i)
}
printf("\n")
}
{ printlist($1) } // call the function for each line of 1st element
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment