0

I'm still learning Unix and I'm having issues understanding the following line of code.

echo "$lines" | awk '{split($0,a,":"); print a[3],a[2],a[1]}'

I don't understand what is happening with the array a in the line of code above. Is it declaring the array and setting it equal to the string it's parsing? If it is declaring the array a, then, why can't I print out the results later on in the code?

echo "${a[1]}"

The line above prints an empty line and not what has been stored in the array a when the string was parsed. I know there is always something in the string that needs to be parsed and when I call the array a[1] I know that I'm in inside the scope. I just don't see/understand what is happening with the array a that prevents me from printing it out later on in the code.

3
  • The awk array a is only available in the awk script; it is not a part of the shell. That's why you can't access it in the echo command later. Commented Apr 30, 2017 at 20:22
  • Then how would I save the array to a variable that I can use? Would it be something like this: VAR=($(echo "$lines" | awk '{split($0,a,":")}')) Commented Apr 30, 2017 at 21:24
  • 1
    Yes (now your comment has been updated to include some code). You might want to use: a=( $(echo "$lines" | awk '{ … }') ) to do a shell array assignment. However, that would process all lines into a single shell array. You'd have to decide whether that's OK. It would also lose any spaces in the array elements (so if one of the lines contained aa bb:cc dd:ee ff gg, you'd get 7 shell array elements from the 3 Awk array elements). You'll have to judge whether that's a problem for you. Commented Apr 30, 2017 at 21:28

1 Answer 1

1

Your code is printing a line for each line of input. If you dont have get output, my first guess would be, that you don't have input.

Given an input of:

lines="ab:cd:ef
ij:kl:m"

the output is:

ef cd ab
m kl ij

awk is executing the commands (which is everything in between the single quotes) for each line of input. First splitting the input line $0 at each : into an array a, then printing the first three elements in reverse order.

If you try to access an array element in the shell, what echo suggests, then you are too late. The array exists within awk and is gone when awk has finished.

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

Comments

Your Answer

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