π Weekend Read π
Many years ago, @WardCunningham has written a beautiful AWK script to calculate the expenses of their skip trip.
https://t.co/N8K6BVDFyx
π‘ This is AWK at its best.
π€ Do you want to write better and portable AWK scripts?
Of course you want π
π‘ GAWK (GNU AWK) supports --lint:
> awk --lint 'and($1,$2)' file.txt
awk: cmd. line:1: warning: `and' is a gawk extension
π€ Do you find your scripts with all these $1, $2 etc unreadable? π€
π‘ Try giving them names:
> docker ps | awk 'BEGIN{cont_id=1;image=2;}$image=="postgres"{print $cont_id}'
π€ How to delete empty lines from a file? π€
awk NF file.txt
π‘ NF is the number of fields. If the number of fields is 0, AWK does not print the line, but in all other cases, the line is just printed.
π€ New week new trick! π€
π€ Replace a string in AWK:
> awk '{gsub("bob", "anna")}1' file.txt
β‘οΈ replace "bob" with "anna"
β‘οΈ 1st param can be a regex (eg. /bob/)
β‘οΈ 3rd param is optional (default $0 / line)
π‘sed might be more suitable for such tasks π
> awk 'NR%2 {print $1}' file.txt
anna
chad
π¨βπ¨ This prints odd lines, because %2 (modulo 2) returns 0 if the NR is divisible by 2. Since 0 is false, those lines are not printed.
β‘οΈ The block is easy: just print the first column
π€ Did you know you can write a self-contained AWK script? π€
β‘οΈ Given a file:
> cat script.awk
#!/usr/bin/awk -f
{ print $0 }
β‘οΈ Make it executable
> chmod +x script.awk
β‘οΈ And run it
> ./script.awk file.txt
π§ If only everything was so easy #Linux π§
π Last July, @lexfridman interviewed Brian Kernighan, one of the authors of AWK. Listen to Brian explaining why AWK is still very useful today.
https://t.co/2UndCrs8xO