awk with if statements

68,791

Solution 1

You should use -v option of awk:

awk -F',' -v accNum="$1" '$1 == accNum {print $3,$2}'

With $1 in double quote, the shell will handle all its special character ( if has ) for you.

Solution 2

You have:

accountNum=$1
awk -F',' '{ if($1==accountNum) { print $3.$2 } }' Accounts

How does the shell variable accountNum get into awk? It doesn't: you need to provide its value to awk explicitly. You can use:

awk -F',' '{ if($1=='"$accountNum"') { print $3.$2 } }' Accounts

which leaves single quotes and has the shell substitute the value of its variable into the awk command, then reenters single quotes for the rest of the command string.

A better or at least more idiomatic script would be:

#!/bin/sh
accountNum=$1
awk -F, '$1 == "'"$accountNum"'" { print $3,$2 }' Accounts

which deals with non-numeric account numbers (quoting the substituted variable), uses a pattern block instead of an explicit if (the {} block will run if the test before it is true), and prints a space between the names as you wanted (because of ,). If you prefer to use if explicitly, move the test inside your existing if statement.

Depending on your real goal awk may not be the best fit for what you're doing. The above still fails if the script's $1 has quotes in it. The shell loop you had wasn't doing anything useful, although it would have repeated the output many times.

Solution 3

Your script already practically does the job without any awk at all:

while IFS=, read -r num last first
    do  [ $((num==accountNum)) -eq 1 ] && 
        printf '%s.%s\n' "$first" "$last"
done < Accounts

I'm not suggesting that this is a better or more efficient solution than using awk alone, but if you want the while...read loop, this certainly beats separate awk processes per each line. Just an FYI, I guess.

Solution 4

#!/bin/bash

awk -v a="$1" -F ',' '$1 == a { print $3, $2 }' Accounts

With -v a="$1" we set the awk variable a to the value of the script's first command line argument, then we specify that the input is comma separated with -F ','. If the first column is equal to the value of a, print the two other columns in reverse order.

You get nothing in your output as you are comparing the first column to the awk variable accountNum, which is unset.

Had there been an entry whose first column had 0 (zero) in it, that entry would have been printed. This is because the value of unset variables in awk evaluates to zero.

Share:
68,791

Related videos on Youtube

gkmohit
Author by

gkmohit

I am an Entrepreneur, Web Designer and Online Business Consultant. My mission is to help small businesses grow by leveraging the power of the internet. I believe in automating tasks by using tools so that you can focus on your core business. I have always been a curious person. The first time I used a computer was in grade 8 and fascinated by how you could create digital art using Corel Draw. In class 10, I had the opportunity to use the first mobile phone, and I was very intrigued by how the OS integrated with the hardware. That same curiosity led me to write my first piece of code in grade 10, and I then realized the power a programmer had in this world. In the mid-2011 family and I moved from Bangalore, India to Toronto, Canada, where I started my undergraduate degree in Computer Science at York University. As a student, I couldn't wait to get some industry experience, and I was fortunate to land my first job in IT at the University Information Technology department. I started as a Technical Analyst and slowly grew to be a software developer at the Student Information System. Gaining some industry experience gave me the confidence to go and attend a few hackathons across North America. I was fortunate to win a few awards from companies like Google, IBM, Bank of Nova Scotia and more while attending hackathons. With the help of my awards, experience and my skills, I started my internship at SAP Labs in Waterloo, Canada. My course was great, but I was seeking something more challenging, so my hackathon team members and I decided to start a fast-growing development shop Hyfer Technologies. At Hyfer Technologies, I stumbled upon Product Management and Business Analysis while managing a team of developers remotely. So far, I have been able to work with 10+ clients from conception to production. As a product manager, I have had a few failed projects but also some that are still growing strong. As of March 2020, I am working with The Ottawa Hospital as a Business Analyst. As a Product Manager &amp; Business Analyst, my skills include but are not limited to: Management Strategy Growth Strategy Customer, partner and client relations, Organizational Design Process Improvements Statistical Analysis and Data Mining Marketing and Brand Strategy Running Product-Related Sessions Managing technical team Through these skills and experience, I am confident I can add a lot of values to any growing team. I am always open to learning more about you and your business. Feel free to reach out to me or follow me on LinkedIn.

Updated on September 18, 2022

Comments

  • gkmohit
    gkmohit almost 2 years

    I am trying to print from a file using awk, but my output is empty. Here is my code so far

    accountNum=$1
    while read -r LINE || [[ -n $LINE ]] ; do
                awk -F',' '{ if($1==accountNum) { print $3.$2 } }' Accounts
    done < Accounts
    

    I have also tried this:

    accountNum=$1
    while read -r LINE || [[ -n $LINE ]] ; do
                echo $LINE  | awk -F',' '{ if($1==accountNum) { print $3.$2 } }' 
    done < Accounts
    

    The input file is :

    1,Doe,John
    2,Rooney,Wayne
    3,Smith,Will
    4,Crow,Russel
    5,Cruise,Tom
    

    The expected output when I run the file is

    $./file.sh 3
    Will Smith
    

    But I get the following

    $./file.sh 3
    $
    

    That is nothing is being printed out. I know the solution with cut, but I want to use awk.

  • gkmohit
    gkmohit almost 10 years
    are you saying I should remove the while loop? :)
  • Michael Homer
    Michael Homer almost 10 years
    At least for the examples it isn't doing anything to help you.
  • Paul_Pedant
    Paul_Pedant about 4 years
    Not just one awk for every line, but that awk reads the entire file again for every line that the shell itself reads. Way to get a O(n^2) algorithm.