0

If I have this awk command...

echo $line | awk '{split($0,array,"|")}'

...how can I use array later in the bash program? If I try to print out information from the array later it's just empty.

2
  • you can't it's an awk variable. Commented Apr 21, 2016 at 23:37
  • the best you can do is output the arr values you need and capture them in the shell, i.e.bashVars=$(echo "$line" | awk '{n=split($0,arr,"|"); print arr[1] " " arr[n] }' ) . for example will print the first and last value from each line and assign to a single shell var bashVar. You can get fancy and declare that var as an arr var if need be. Good luck. Commented Apr 21, 2016 at 23:42

3 Answers 3

5

You can't access awk variables outside of awk, but you can do the same using bash arrays directly

$ IFS='|' read -r -a array <<< "a|b|c"; echo ${array[1]} 
b
Sign up to request clarification or add additional context in comments.

Comments

2

You can use awk array contents outside of awk if you print it:

IFS=$'\n' read -d '' -r -a line < <(echo 'o|p|s' | awk '{split($0,array,"|"); for (i in array) print array[i]}')
declare -p line
# OUTPUT: declare -a line='([0]="o" [1]="p" [2]="s")'

Comments

1

An other solution in bash if I presume that fields haven't got space then only 1 assignment.

ln="apple|lemon|orange|strawberry"    # eg

v=(${ln//|/ })     # substitute | with " " and vectorising with () 
# Now we are ready

# checking it:
for((i=0;i<${#v[@]};i++));do echo ${v[$i]}; done
apple
lemon
orange
strawberry

#or:
for i in ${v[@]}; do echo $i; done
apple
lemon
orange
strawberry

If we have some space but no underline "_" we need 3 steps.

ln="api ple|l em  on|ora  nge|s traw   berry"
echo "$ln"
api ple|l em  on|ora  nge|s traw   berry
ln=${ln// /_}                             # 1st
echo "$ln"
api_ple|l_em__on|ora__nge|s_traw___berry
v=(${ln//|/ })                            # 2nd
for i in ${v[@]}; do echo $i; done
api_ple
l_em__on
ora__nge
s_traw___berry
for((i=0;i<${#v[@]};i++));do v[$i]="${v[i]//_/ }"; done  # 3rd
for((i=0;i<${#v[@]};i++));do echo "${v[$i]}"; done
api ple
l em  on
ora  nge
s traw   berry

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.