Awk ward problem

awk

I'm trying to use awk to pull some different fields from a string.

Example:

selected="a2.flac|a3.flac|a4.flac"
first_file=$(echo "$selected" | awk -F'|' '{print $1}')

The above code returns a2.flac which is what I expected. But now, I want to iterate over a variable and pull each file out one at a time. So I tried this:

i=1
first_file=$(echo "$selected" | awk -F'|' '{print $i}')

I thought this would pull out the first file … but nothing returns.
so I tried this next:

i=1
first_file=$(echo "$selected" | awk -F'|' '{print \$i}')

This also did not work. I also tried this method:

i=1
first_file=$(echo "$selected" | awk -F'|' n=$i '{print $n}')

And also tried this:

i=1
first_file=$(echo "$selected" | awk -v -F'|' n=$i '{print $n}')

Nothing I've tried seems to work. I'm at a loss on what will work.

Best Answer

you almost make it

i=1
first_file=$(echo "$selected" | awk -v n="$i" -F'|'  '{print $n}')
  • variable are set using -v name=value
Related Question