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.
-
is this a homework assignment?Eddie– Eddie2012-03-05 00:26:53 +00:00Commented 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.user1248799– user12487992012-03-05 00:30:05 +00:00Commented Mar 5, 2012 at 0:30
Add a comment
|
5 Answers
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
1 Comment
user1248799
thanks. i got it to work with arrays though since i posted the question.
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
user1248799
what do the 3 < symbols do after the \n?