1

lets say i used grep and cut to store data into variables. i need to get the first second and third values of each variable concatenated with each other. i think i need to use arrays to achieve this but i don't know how to go about doing that. for example if $one holds a b c and $two holds 1 2 3 and $three holds x y z i want to concatenate so that my output would look like a1x b2y c3z. like i said i think i need to store my grep/cut output into an array but i am not sure how to do that. Thanks.

2
  • is this a homework assignment? Commented Mar 5, 2012 at 0:26
  • yes this is a homework assignment. i grep line of a file and cut certain characters out of the grep output. Commented Mar 5, 2012 at 0:30

5 Answers 5

1

In pure bash, you can do something like this:

v1="a b c"
v2="1 2 3"
v3="x y z"
for v in v1 v2 v3; do
  read p1 p2 p3 <<< ${!v}
  a1="$a1$p1" 
  a2="$a2$p2" 
  a3="$a3$p3" 
done
echo $a1 
echo $a2 
echo $a3

The last three echoes output:

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

1 Comment

thanks. i got it to work with arrays though since i posted the question.
1

This might work for you:

v1="a b c"
v2="1 2 3"
v3="x y z"
parallel --xapply echo {1}{2}{3} ::: $v1 ::: $v2 ::: $v3
a1x
b2y
c3z

Comments

0

You can use sed,tr,etc to translate ' ' to '\n'.
Then use paste to concatenate them vertically.

$ v1="a b c"
$ v2="1 2 3"
$ v3="x y z"

$ paste <(tr ' ' '\n' <<<$v1) <(tr ' ' '\n' <<<$v2) <(tr ' ' '\n' <<<$v3) | tr -d '\t'
a1x
b2y
c3z

Or

$ paste <(echo "${v1// /$'\n'}") <(echo "${v2// /$'\n'}") <(echo "${v3// /$'\n'}") | tr -d '\t'
a1x
b2y
c3z

Note: If you save them in separated files, It will be much easier.

1 Comment

what do the 3 < symbols do after the \n?
0

Another solution in pure bash using an array :

$ arr=( $v1 $v2 $v3 )

$ for ((i=0; i<3; i++)); do
    for ((j=i; j<${#arr[@]}; j+=3)); do printf '%s' ${arr[j]}; done
    echo
 done

a1x
b2y
c3z

Comments

0

Pure bash using an array:

declare -a a=( $v1 $v2 $v3 )

echo "${a[0]}${a[3]}${a[6]}"
echo "${a[1]}${a[4]}${a[7]}"
echo "${a[2]}${a[5]}${a[8]}"

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.