5

I have a simple awk one liner that folds the next line onto the current line when a given pattern is matched. Here it is:

awk '/two/ { printf $1; next; } 1' test.txt 

with the following input:

one
two
three
four
five
six

one
two
three 
four

you get:

one
twothree
four
five
six

one
twothree 
four

Note that the "three" is folded up with the "two" which is what I wanted to occur. I found this solution (don't remember where) and thought it odd that the trailing '1' appeared to be the missing piece that resulted in the desired effect. If you take it out, you get:

awk '/two/ { printf $1; next; }' test.txt 
twotwo

As the result. So my question is, what does the trailing '1' do, and where is it documented?

Thanks!

Damon Snyder
  • 1,362
  • 1
  • 11
  • 18

3 Answers3

6

For awk, 1 mean true, and when an expression is true, awk print the current line by default.

Examples :

  • awk '1' /etc/passwd will print the whole file
  • awk '0' /etc/passwd will not print the whole file

If you're good in arithmetic (or you have imagination or programming skills), there's many tricks you can do with this behaviour.

Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223
3

"The '1' at the end of whole Awk one-liner prints out the modified line (it's syntactic sugar for just "print" (that itself is syntactic sugar for "print $0"))".

-- catonmat

blueberryfields
  • 45,910
  • 28
  • 89
  • 168
1

You got your answer to your specific question BUT your posted script is unsafe. The first argument for printf is a format string, not data. You can sometimes use it to print data but only when it's hard-coded in your script, not when you're reading it from input. Look what happens if your input happens to contain a printf formatting string:

$ cat file
one
two%s
three
four

$ awk '/two/ { printf $1; next; } 1' file
one
awk: cmd. line:1: (FILENAME=file2 FNR=2) fatal: not enough arguments to satisfy format string
        `two%s'
            ^ ran out for this one

The correct way to write the script is:

$ awk '/two/ { printf "%s",$1; next; } 1' file
one
two%sthree
four
Ed Morton
  • 188,023
  • 17
  • 78
  • 185