1

I have the following code that results in a "Permission denied" error. It is supposed to get the nth word of a string and store it to a variable. If I use it with echo, it works just fine, but produces the error when trying to save it to a variable.

a="one two three four five six"
N=2
b=$($a | awk -v N=$N '{print $N}')
echo $b

What could the problem be?

primix
  • 355
  • 1
  • 8
  • 1
    Heh. The reason you probably couldn't find any duplicates for this is that most often `$a` isn't a valid file or command name, so people making the same mistake usually get "file not found". In your case I'm assuming your real data is not `"one two three four five six"` but the name of a file that doesn't have executable permission, hence "permission denied". – Charles Duffy Jan 19 '20 at 15:04
  • ... That's part of why it's important to test that even after you anonymized your data your code still gives the error you're asking about. – Charles Duffy Jan 19 '20 at 15:06

1 Answers1

1

You should use echo for variable printing like as follows:

a="one two three four five six"
N=2
b=$(echo "$a" | awk -v N=$N '{print $N}')
echo $b

OR use like <<<"$var" for sending input to awk command:

a="one two three four five six"
N=2
b=$(awk -v N=$N '{print $N}' <<<"$a")
echo $b

When we are running command without echo it is considered as a command which is NOT so we get error like line 3: one: command not found so to send Input to awk command use anyone of the above mentioned commands.

RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93