Kishore Sai
Kishore Sai

Reputation: 11

Awk Not ignoring white spaces

My input file is in this format

         input
         input
         output
         super
         krish

that is every line starts with white space and have something after whitespaces.

Now when i try "awk '{print $1}' input" in unix it is printing in the below format

$ awk '{print $1}' input
input
input
output
super
krish

But the problem is when I try

awk '{if(\$1 == input) print \$1;}' <file>

in system or by using backticks it is not printing the output, neither it is showing any error

Can anyone help me in this??

Upvotes: 1

Views: 680

Answers (2)

kvantour
kvantour

Reputation: 26471

The problem in your initial code is that you wrote input without any quotes. This actually implies that input is a variable which is defaultly assigned as an empty string in case of string operations or as the number zero in case of numeric operations.

awk '{if($1 == input) print $1;}' <file>

is therefore equivalent to (in case of string comparisons)

awk '{if($1 == "") print $1;}' <file>

So the correct answer would be any of the following :

awk '{if ($1 == "input") print $1 }' <file>
awk '($1 == "input"){print $1}'      <file>
awk '$1~/^input$/{print $1}'         <file>

If your file only has a single column, and you want to keep the original spacing:

awk '{if ($1 == "input") print}'        <file>
awk '($1 == "input")'                   <file>
awk '$1~/^input$/'                      <file>
awk '/^[[:blank:]]*input[[:blank:]]*$/' <file>

note: the regex operation /.../ does not require quotes. So /input/ works.

note: escaping the $ sign using \$ does not work. The \ is assumed to be the line-break character and is expected to be the last character on the line. So the original code breaks.

Upvotes: 0

RavinderSingh13
RavinderSingh13

Reputation: 133428

In case you want to print those lines which have input string in their first field then following will help you.

awk '$1=="input"'  Input_file

Output will be as follows:

     input
     input

In case you don't want to have spaces and print those lines whose first field is input then following may help you.

awk '$1=="input"{$1=$1;print}' Input_file

Output will be as follows:

input
input

Upvotes: 1

Related Questions