3 ms·
One tip I have to make large-ish awk programs readable is to name the columns in the BEGIN section. Then, you'd use $colname instead of $1, $2, etc. for instanc
by ketanmaheshwari 5y ago
One tip I have to make large-ish awk programs readable is to name the columns in the BEGIN section. Then, you'd use $colname instead of $1, $2, etc. for instance:
BEGIN{
item_type = 1;
item_name = 2;
price = 3;
sale = 4;
#etc
}
Now, in place of $1, you'd say $item_type which significantly improves overall readability of the code.
- ulucs 5y agoNice tip, so basically like excel with tables
- jayknight 5y agoI've also used this to address columns by name for files with lots of columns that I'm too lazy to count: https://unix.stackexchange.com/a/359699 https://unix.stackexchange.com/a/359699
- dredmorbius 5y agoYou can also put a similar code block at the start of a general processing entry. This applies on both flat (uniform record) and hierarchical (multiple record-type) data. E.g.: { name = $1 dob = $2 grade = $3 # ... # Do stuff with name / dob / grade, etc. } If the data are structured, so that there are multiple record types (typically defined by prefix or some other regex) you can put variable assignments within each block. /^rectype1/ { var1 = $1; var2 = $2, ... } /^rectype2/ { varA = $1; varB = $2, ... } I prefer to leave BEGIN blocks for defining constants or tables and such.
- ketanmaheshwari 5y agoI prefer using colname = n (as opposed to colname = $n) so I can use $colname so as to distinguish the column names from local variables.
- dima55 5y agoIf you want to do that, use vnlog instead. You're 90% there already. It formalizes the idea of a header to label columns, and allows normal unix data-processing tools to just work with those labels. Your awk use case is quite literally "vnl-filter --eval" https://github.com/dkogan/vnlog/ https://github.com/dkogan/vnlog/
- 1vuio0pswjnm7 5y agoGood on the author for listing other similar programs. I have been testing one of them, datamash. Its documentation claims it is faster than uniq in some situations.