1

I am writing a script, and I have delimited file that looks like this.

1|Anderson|399.00|123                                  
2|Smith|29.99|234                                  
3|Smith|98.00|345                                   
4|Smith|29.98|456                                   
5|Edwards|399.00|567  
6|Kreitzer|234.56|456

Here's an awk statement that will grab all the values in column one of a row that contain "Smith".

echo $(awk -F '|' 'BEGIN {count=0;} $2=="Smith" {count++; print $1}' customer)

The output would be:

2 3 4

How could I make it so I am also inputting the values into an array as awk increments. I tried this:

echo $(awk -F '|' 'BEGIN {count=0;} $2=="Smith" {count++; arr[count]=$1; print $1}' customer)

Edit: Later into the script, when I type

echo ${array[1]} 

nothing outputs.

3
  • and?????????????????????????? Commented Mar 11, 2013 at 7:00
  • 2
    You cannot transfer arrays from awk to the shell. arr[count] is in awk, ${array[1]} is in shell. Perhaps you are looking for the END section? Commented Mar 11, 2013 at 7:37
  • Oh, well that makes sense.. How would you implement the END section in such a way that I can use the array throughout the rest of the script? Commented Mar 11, 2013 at 7:42

3 Answers 3

1

Your code seems to be right! Perhaps, I might haven't got your question correctly?

I slightly enhanced your code to print the values stored in the array at the end of execution. Also, there is a print statement just before the values are printed.

echo $(awk -F '|' 'BEGIN {count=0;} $2=="Smith" {count++; arr[count]=$1; print $1} END { print "Printing the inputs"; for (i in arr) print  arr[i] }' customer)
2 3 4 Printing the inputs 2 3 4

Further, look at this site for more examples.

Sign up to request clarification or add additional context in comments.

1 Comment

Oh. Your's works. For some reason, when I type echo ${array[1]} on the next line down, it doesn't work
0

Your question is not very clear. Looking for something like this?

awk -F "|" '$2=="Smith" {arr[count++]=$1}
            END {n=length(arr); for (i=0;i<n;i++) print (i+1), arr[i]}' in.file

OUTPUT

1 2
2 3
3 4

1 Comment

I simply want to take the output, and put it into an array. So the array should look like arr[0]=2, arr[1]=3, arr[2]=4. However, later into my script, when I type "echo ${array[1]}" nothing is outputted.
0

Found an easy solution. Set the output of awk into a variable. Then turn the variable into an array.

list=$(awk -F '|' 'BEGIN {count=0;} $2=="Smith" {count++; print $1}' customer)

array=($list)

Typing:

echo ${array[1]}

Will give you the second entry in the array

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.