Awk print exact fields when finding an exact match

Viewed 537

I have a persons.dat file containing information.

Here's an example line.

1129|Lepland|Carmen|female|1984-02-18|228T04:39:58.781+0000|81.25.252.111|Internet Explorer

1129 is the ID.

I am asked to display the information of anyone based on their ID,in particular their firstname (Carmen), (Lastname = Lepland) and date of Birth (1984-02-18) separated by a space.

I have stored the id in a shell variable IDNumber as shown below:

for arg1 in $@;do # Retrieve ID Number
if  [ $1 = "-id" ];then
        IDNumber="$2"
fi
shift
done

How can I use awk to display the exact fields of one ID?

1 Answers

The command line argument parsing of the shell script is a bit confusing like that, since arg1 is not used. And even after it finds -id and assigns $2 to IDNumber, the iteration continues. For example when the arguments are -id 3, after IDNumber=3, the iteration continues, checking if [ 3 = "-id" ]. Also, the "$1" in if [ $1 = ... ] should be double-quoted, otherwise the script will crash if there is an empty argument.

Here's one way to fix these issues:

while [ $# -gt 0 ]; do
    if [ "$1" = -id ]; then
        id=$2
    fi
    shift
done

Then you can use id with Awk like this:

awk -F'|' -v id="$id" '$1 == id {print $3, $2, $5}' persons.dat

That is:

  • Set | as the field separator
  • Set id variable in Awk to the value of $id in the shell
  • Find the record in the input where the first field ($1) is equal to id
  • Print the columns you need
Related