# Understanding $0=$2 in awk

DevFeed: [Understanding $0=$2 in awk](<https://devfeed.tech/articles/what-does-0-2-in-awk-do-learn-awk-25222.md>)

Original publisher: [Read original article](<https://kau.sh/blog/awk-1-oneliner-dollar-explanation/>)

Author: Kaushik Gopal

Published: 2022-09-24T07:22:16Z

Content type: tutorial

Language: en

Sources: [Kaushik Gopal's Site](<https://devfeed.tech/sources/kaushik-gopal-s-site.md>)

Topics: [Programming](<https://devfeed.tech/topics/programming.md>), [Code](<https://devfeed.tech/topics/code.md>)

Tags: [code](<https://devfeed.tech/tags/code.md>), [programming](<https://devfeed.tech/tags/programming.md>)

## AI overview

A tutorial that explains awk defaults by breaking down the expression `$0=$2`, including field delimiters, pattern matching, default actions, and variable reassignment.

## Source excerpt

The trick to understanding awk in all its terse glory is to understand its defaults. I made a screencast explaining how awk works by deconstructing a script I'd previously written for this blog .1 In this post we'll look at deconstructing awk's defaults so we can understand all those one-liner scripts stack overflow solutions throw your way. The example # I have a file that contains the version info for my apps and I'd like to extract the first version number in there: // appVersion.gradle def baseCode = 30001 def appVersion = [ product-1 : [ name: "21.091.420", code: baseCode ], product-2: [ name: "20.090.300", code: baseCode ], //... // I want to pluck 21.091.420 from this file The first solution (meh) # Some quick googling revealed this stack overflow solution which gets us close: gawk -F'"' '$0=$2' appVersion.gradle # -- output -- # 21.091.420 # 20.090.300 I only require the first number though so a quick way2 to do this would just be: gawk -F'"' '$0=$2' appVersion.gradle | head -n 1 # -- output -- # 21.091.420 The problem with solution 1 # awk is powerful and to reach out to head for that last teeny tiny mile seemed sacrilegious. I want this solution to be pure awk. What the heck does that incantation gawk '$0=$2' do? 3 The basics # Let's try to take that script apart piece by piece: default input field delimiter ## gawk -F'"' '$0=$2' appVersion.gradle # ↑ # input field delimiter If you don't specify the input field delimiter, awk sensibly defaults to the space character. Let's try some examples: echo "Hello kind world" | gawk '{print $2}' echo "Hello kind world" | gawk -F" " '{print $2}' # -- output -- # kind echo "Hello kind world" | gawk -F"," '{print $2}' # -- no output -- Notice how the line is split into numbered "segments" where $1, $2, $3 hold the first three words in our example respectively. $0 represent the entire line. default syntax ## If you watched my screencast you'll remember that awk's general syntax is as follows: awk ' BEGIN { a1; a2; a3; }