Print dollar sign in bashscript (which uses awk)

I want to use awk in my bashscript, and this line obviously does not work:

line="foo bar" echo $line | awk '{print $1}' 

How to avoid $1 , so it is not replaced by the first argument to the script?

+6
source share
2 answers

Your script (with single quotes around an awk script) will work as expected:

 $ cat script-single #!/bin/bash line="foo bar" echo $line | awk '{print $1}' $ ./script-single test foo 

Next, the following will be broken (the script displays an empty string):

 $ cat script-double #!/bin/bash line="foo bar" echo $line | awk "{print $1}" $ ./script-double test​ 

Note the double quotes around the awk program.

Because double quotes extend the $1 variable, the awk command will get a script {print test} that prints the contents of the awk test variable (which is empty). Here is a script that shows that:

 $ cat script-var #!/bin/bash line="foo bar" echo $line | awk -v test=baz "{print $1}" $ ./script-var test baz 

Related Reading: Bash Reference Guide - Citation and Shell Extensions

+8
source

As currently written, $ 1 will not be replaced (since it is in single quotation marks, bash will not parse it)

If you write awk "{print $1}" , bash will expand $1 in the double-quoted string

Please note that the rules for expanding variables depend on the external citation level, so $1 in "awk '{print $1}'" will be expanded

+4
source

Source: https://habr.com/ru/post/952157/


All Articles