Skip to content

Commit cf32cd7

Browse files
corrections and added couple of gotchas
1 parent c10cf00 commit cf32cd7

File tree

1 file changed

+37
-1
lines changed

1 file changed

+37
-1
lines changed

gnu_awk.md

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1125,6 +1125,7 @@ $ awk '/are/{if(sub("so", "SO")) print}' poem.txt
11251125
And SO are you.
11261126
$ # of course, can also use
11271127
$ awk '/are/ && sub("so", "SO")' poem.txt
1128+
And SO are you.
11281129

11291130
$ # if-else example
11301131
$ awk 'NR>1{if($2>40) $0="+"$0; else $0="-"$0} 1' fruits.txt
@@ -1339,6 +1340,7 @@ a
13391340
* If there are lots of strings to check, use arrays
13401341

13411342
```bash
1343+
$ # can also use BEGINFILE instead of FNR==1
13421344
$ awk 'FNR==1{s1=s2=0} /is/{s1=1} /are/{s2=1} s1&&s2{print FILENAME; nextfile}' *
13431345
poem.txt
13441346
sample.txt
@@ -2054,7 +2056,7 @@ Amy 67
20542056
## <a name="awk-scripts"></a>awk scripts
20552057

20562058
* For larger programs, save the code in a file and use `-f` command line option
2057-
* `;` is not needed to terminate a command
2059+
* `;` is not needed to terminate a statement
20582060
* See also [gawk manual - Command-Line Options](https://www.gnu.org/software/gawk/manual/html_node/Options.html#Options) for other related options
20592061

20602062
```bash
@@ -2472,6 +2474,40 @@ $ echo 'foo good 123' | awk '{printf $2 | "wc -c"; printf $3 | "wc -c"}'
24722474
24732475
## <a name="gotchas-and-tips"></a>Gotchas and Tips
24742476
2477+
* using `$` for variables
2478+
* only input record `$0` and field contents `$1`, `$2` etc need `$`
2479+
* See also [unix.stackexchange - Why does awk print the whole line when I want it to print a variable?](https://unix.stackexchange.com/questions/291126/why-does-awk-print-the-whole-line-when-i-want-it-to-print-a-variable)
2480+
2481+
```bash
2482+
$ # wrong
2483+
$ awk -v word="apple" '$1==$word' fruits.txt
2484+
2485+
$ # right
2486+
$ awk -v word="apple" '$1==word' fruits.txt
2487+
apple 42
2488+
```
2489+
2490+
* dos style line endings
2491+
* See also [unix.stackexchange - filtering when last column has \r](https://unix.stackexchange.com/questions/399560/using-awk-to-select-rows-with-specific-value-in-specific-column)
2492+
2493+
```bash
2494+
$ # no issue with unix style line ending
2495+
$ printf 'foo bar\n123 789\n' | awk '{print $2, $1}'
2496+
bar foo
2497+
789 123
2498+
2499+
$ # dos style line ending causes trouble
2500+
$ printf 'foo bar\r\n123 789\r\n' | awk '{print $2, $1}'
2501+
foo
2502+
123
2503+
2504+
$ # easy to deal by simply setting appropriate RS
2505+
$ # note that ORS would still be newline character only
2506+
$ printf 'foo bar\r\n123 789\r\n' | awk -v RS='\r\n' '{print $2, $1}'
2507+
bar foo
2508+
789 123
2509+
```
2510+
24752511
* relying on default intial value
24762512
24772513
```bash

0 commit comments

Comments
 (0)