1

I'm trying to awk a file which contains a list of names mapped to DOB in DD-MM format.

The match didn't work in attempt 1), so I tried to run it on the command line as per attempt 2), but that still didn't work. Any suggestions?

Thanks

file.txt
jason 08-04

ATTEMPT 1

XXXXXX$ cat a.txt
#!/bin/bash

file="file.txt"

current_date=$(date +%d-%m)
awk -F" ", 'if ($2==$current_date) print $1)' "$file"

ATTEMPT 2

awk -F" ", '{
if ($2=='08-04')
   print "$1"
}' file.txt

2 Answers 2

3

A few issues in both your attempts:

Attempt#1 issues:

  • the variable $current_date was not interpolated within single quotes
  • misplaced comma after field separator awk -F" ", <--
  • attempt to use if operator outside the awk's action delimiters { ... } - will throw syntax error ...

Attempt#2 issues:

  • misplaced comma after field separator awk -F" ", <--
  • broken single quoting '...'08-04'...'

The right way (passing a variable into awk command as an argument):

awk -v d="$curr_date" '$2==d{ print $1 }' "$file"
1

For attempt 1, you'll need to use double quotes for the variable to be expanded by the shell, but that will cause problems with things like $1. I'd suggest rewriting it so:

awk -v current_date="$(date +%d-%m)" '$2 == current_date {print $1}' "$file"

Here, we set an awk variable current_date using the -v option.

In attempt 2, using single quotes inside the single-quoted string just exited the quote. You should use double quotes for awk strings, and shouldn't quote $1:

awk '$2 == "08-04" {print $1}' file.txt

In both attempts, I don't understand why you use -F" ",. By default, awk splits on whitespace, so you can just omit the field separator for the example input shown and the , is entirely superfluous. Also, often awk expressions like {if (A) B} can be rewritten as just A {B}, which is more idiomatic for awk.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .