Madan
Madan

Reputation: 75

AWK array parsing issue

My two input files are pipe separated.

File 1 :

a|b|c|d|1|44

File 2 :

44|ab|cd|1

I want to store all my values of first file in array.

awk -F\| 'FNR==NR {a[$6]=$0;next}'
  1. So if I store the above way is it possible to interpret array; say I want to know $3 of File 1. How can I get tat from a[].

  2. Also will I be able to access array values if I come out of that awk?

Thanks

Upvotes: 0

Views: 80

Answers (2)

MarcM
MarcM

Reputation: 2251

To keep it simple, you can reach your goal of storing (and accessing) values in array without using awk:

arr=($(cat yourFilename |tr "|" " ")) #store in array named arr

# accessing individual elements
echo ${arr[0]}  
echo ${arr[4]}

# ...or accesing all elements
for n in ${arr[*]}
do
    echo "$n"
done

...even though I wonder if that's what you are looking for. Inital question is not really clear.

Upvotes: 0

Wintermute
Wintermute

Reputation: 44043

I'll answer the question as it is stated, but I have to wonder whether it is complete. You state that you have a second input file, but it doesn't play a role in your actual question.

1) It would probably be most sensible to store the fields individually, as in

awk -F \| '{ for(i = 1; i < NF; ++i) a[$NF,i] = $i } END { print a[44,3] }' filename

See here for details on multidimensional arrays in awk. You could also use the split function:

awk -F \| '{ a[$NF] = $0 } END { split(a[44], fields); print fields[3] }'

but I don't see the sense in it here.

2) No. At most you can print the data in a way that the surrounding shell understands and use command substitution to build a shell array from it, but POSIX shell doesn't know arrays at all, and bash only knows one-dimensional arrays. If you require that sort of functionality, you should probably use a more powerful scripting language such as Perl or Python.

If, any I'm wildly guessing here, you want to use the array built from the first file while processing the second, you don't have to quit awk for this. A common pattern is

awk -F \| 'FNR == NR { for(i = 1; i < NF; ++i) { a[$NF,i] = $i }; next } { code for the second file here }' file1 file2

Here FNR == NR is a condition that is only true when the first file is processed (the number of the record in the current file is the same as the number of the record overall; this is only true in the first file).

Upvotes: 1

Related Questions