Hi,
Here is my code,

ids=(1 5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 90 100 110 120)
for ((i=0;i<${#ids};i++)); do
   awk '{ print ${ids[${i}]}" "$1; }' > ${TMP} < ./results/$1${ids[${i}]}/test_error.dat
done

I got this error

awk: { print ${ids[${i}]}" "$1; }
awk: ^ syntax error
awk: { print ${ids[${i}]}" "$1; }
awk: ^ syntax error
awk: fatal: invalid subscript expression

if I changed awk to gawk, I will get this error

gawk: {print ${ids}" "$1;}
gawk: ^ syntax error
gawk: {print ${ids}" "$1;}
gawk: ^ syntax error

Could you please explain what mistake I made? THanks a lot!

Your script doesn't make any sense, however I am going to guess some.
If you want to itinerate through the array ids you are missing something

for ((i=0;i<${#ids[@]};i++)); do

> ${TMP} < ./results/$1${ids[${i}]}/test_error.dat

That redirection is all backward.
It would have been < inputfilename > outputfilename.
However awk doesn't need redirection for the inputfilename.

You can't use expanding ${} notation with awk since the ($) signify the fields and ({}) are for actions.

Hi,
Here is my code,

ids=(1 5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 90 100 110 120)
for ((i=0;i<${#ids};i++)); do
   awk '{ print ${ids[${i}]}" "$1; }' > ${TMP} < ./results/$1${ids[${i}]}/test_error.dat
done

I got this error


if I changed awk to gawk, I will get this error


Could you please explain what mistake I made? THanks a lot!

1. You mixed metaphors, so to speak. As Aia said, you cannot (easily) mix shell variables with awk. While gawk does allow you to import shell var values using the -v option, you still won't get what you want, because you are trying to use an awk variable outside of awk (yea verily, even before awk ever runs)!

2. You used entirely insufficient white space. Computer can parse densely-packed code, but humans usually generate errors when they do. Add spaces and you'll more easily see what you did wrong.

I think you looked at the code and assumed that it was all one language. Your shell script is one language. Your awk script is another language. Each runs in its own environment. Neither is compatible with the other.

Given what you seem to be attempting to do, you'll probably have better results if you do it all with gawk:
gawk script file

BEGIN {
  id_cnt = split("1 5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 90 100 110 120", ids);
}
{
  for (i=0; i<id_cnt; i++) {
    while (getline <"./results/" filename_part_one ids[i] "/test_error.dat" > 0) {
      printf("%s %s\n", ids[i], $1);
    }'
done
}

shell script

#! /bin/sh

if [ $# -eq 0]; then echo "need an argument!"; exit 1; fi

gawk -v filename_part_one="$1" -f gawk_script_file > ${TMP}

I'm assuming you expected to specify one argument to your shell script.

Having writ all that, I'm still not sure what you were trying to accomplish.

This article has been dead for over six months. Start a new discussion instead.