1

I am working with a list of DNA sequences. I would like to get all the sequences with the same name ($1). I was thinking to use if ($1 == "$1"). But this does not work.

result_file:

name1 number1 number2 sequenceofname1
name1 number3 number4 sequenceofname1

script:

awk '{if ($1 == "$1") printf("%s_%s_%s \t%s\n", $1,$2,$3,$4);}' <result_file >file.txt

How do I pass $1 to my awk command?

Community
  • 1
  • 1
pickoka
  • 35
  • 2
  • 2
    `$1==$1` will *always* be true as it is an identity. You need to store the value of `$1` you want to match and compare that against each line's `$1` value. – Etan Reisner Aug 20 '15 at 12:00

2 Answers2

3

you can use -v option

awk -v name="name1" '{
  if ($1 == name) printf("%s_%s_%s \t%s\n", $1,$2,$3,$4);
}' result_file > file.txt

or, if this statement in a script

awk -v name="$1" '{
  if ($1 == name) printf("%s_%s_%s \t%s\n", $1,$2,$3,$4);
}' result_file > file.txt

-v var=val, Assign the value val to the variable var, before execution of the program begins. Such variable values are available to the BEGIN block of an AWK program.

Jose Ricardo Bustos M.
  • 8,016
  • 6
  • 40
  • 62
1

If I've understood correctly, you want to use $1 from your shell script as an argument to the awk command within it.

In which case, you want to not quote the $1 that you want expanding, but do quote the rest of the awk command. One possibility is to double-quote the command:

awk "{if (\$1 == \"$1\") printf(\"%s_%s_%s \\t%s\\n\", \$1,\$2,\$3,\$4);}"

It can get hard to manage all the backslashes, so you probably prefer to single-quote most of the command, but double-quote the part to be expanded:

awk '{if ($1 == "'"$1"'") printf("%s_%s_%s \t%s\n", $1,$2,$3,$4);}'

That's slightly tricky to read - the critical bit divides as '...($1 == "' "$1" '")...'. So there's a double-quote that's part of the Awk command, and one that's for the shell, to keep $1 in one piece.

Oh, and no need to invoke cat - just provide the file as input:

awk ...  <result_file >file.txt
Toby Speight
  • 27,591
  • 48
  • 66
  • 103