LinuxQuestions.org
Welcome to the most active Linux Forum on the web.
Go Back   LinuxQuestions.org > Forums > Linux Forums > Linux - Newbie
User Name
Password
Linux - Newbie This Linux forum is for members that are new to Linux.
Just starting out and have a question? If it is not in the man pages or the how-to's this is the place!

Notices


Reply
  Search this Thread
Old 11-11-2011, 03:45 AM   #1
nagendrar
Member
 
Registered: Apr 2008
Location: HYD, INDIA.
Posts: 154

Rep: Reputation: 15
how can we use multiple variables in single for loop in shell script


ch1="a b c d"
ch2="w x y z"

i want to the o/p as
a:w
b:x
c:y
d:z

Here I am implementing as below using for loop but failed to run the script

for i in $ch1, j in $ch2
do
echo $i:$j
done


Please help me to use multiple variables in single for loop in shell script

ThanQ
Nagendra
 
Old 11-11-2011, 04:17 AM   #2
fukawi1
Member
 
Registered: Apr 2009
Location: Melbourne
Distribution: Fedora & CentOS
Posts: 854

Rep: Reputation: 193Reputation: 193
You could do it by cycling through a pair of arrays:
Code:
#!/bin/bash

# Define the arrays
array1=("a" "b" "c" "d")
array2=("w" "x" "y" "z")

# get the length of the arrays
length=${#array1[@]}
# do the loop
for ((i=0;i<=$length;i++)); do
        echo -e "${array1[$i]} : ${array2[$i]}"
done
Code:
~ $ ./tmp.sh 
a : w
b : x
c : y
d : z
Although a more skilled bash-ist will probably have a better way...
 
Old 11-11-2011, 04:44 AM   #3
nagendrar
Member
 
Registered: Apr 2008
Location: HYD, INDIA.
Posts: 154

Original Poster
Rep: Reputation: 15
Thank You for quick reply.
But here ch1 and ch2 are not arrays. Then How can I implement?

please help me.

ThanQ
Nagendra.
 
Old 11-11-2011, 05:17 AM   #4
fukawi1
Member
 
Registered: Apr 2009
Location: Melbourne
Distribution: Fedora & CentOS
Posts: 854

Rep: Reputation: 193Reputation: 193
A conversation with an associate (LQ user fukawi2) informed me that you can convert a space delimited string with:
Code:
array1=(${ch1// / })
array2=(${ch2// / })
so the example would look like:
Code:
#!/bin/bash
ch1="a b c d"
ch2="w x y z"

# Define the arrays
array1=(${ch1// / })
array2=(${ch2// / })

# get the length of the arrays
length=${#array1[@]}

# do the loop
for ((i=0;i<=$length;i++)); do
        echo -e "${array1[$i]} : ${array2[$i]}"
done
 
Old 11-11-2011, 07:47 AM   #5
Juako
Member
 
Registered: Mar 2010
Posts: 202

Rep: Reputation: 84
In this case you don't need arrays, for .. in can iterate over a string with delimiters:

Code:
#!/bin/bash
ch1="a b c d"
ch2="w x y z"
i=0

IFS=" "
for ch in $ch1; do
    echo ${ch1:$i:1} ${ch2:$i:1}
    (( i+=2 ))
done
 
1 members found this post helpful.
Old 11-11-2011, 02:50 PM   #6
David the H.
Bash Guru
 
Registered: Jun 2004
Location: Osaka, Japan
Distribution: Arch + Xfce
Posts: 6,852

Rep: Reputation: 2037Reputation: 2037Reputation: 2037Reputation: 2037Reputation: 2037Reputation: 2037Reputation: 2037Reputation: 2037Reputation: 2037Reputation: 2037Reputation: 2037
Quote:
Originally Posted by fukawi1 View Post
A conversation with an associate (LQ user fukawi2) informed me that you can convert a space delimited string with:

Code:
array1=(${ch1// / })
array2=(${ch2// / })
Actually, the "conversion" itself does nothing. All you're doing is replacing spaces with spaces.

parameter expansion

The array is set by breaking up the input string into words. Words are defined by whitespace (space+tab+newline) by default, so you don't need to do anything special in this case.

Code:
array1=( $ch1 )
Now if the input strings were delimited by a different character, then you can use a substitution to convert them to spaces for word-breaking.

Code:
ch1='a:b:c:d'

array1=( ${ch1//:/ } )
However, if the individual entries themselves include whitespace, then this won't work. They'll be broken up as well. You need to change the default delimiter, the IFS variable, so that it ignores whitespace and only divides on the character you want.

Code:
ch1='a a:b b:c c:d d'

savedifs=$IFS
IFS=":"

array1=( $ch1 )

IFS=$savedifs
Another technique is to use the read command.

Code:
IFS=":" read -a array1 <<<"$ch1"
This is a convenient method because when (most) commands are directly prefixed by a variable setting (not separated by a command terminator), then that setting only affects the invoked command. So we don't need to back up or restore the original IFS setting.

http://mywiki.wooledge.org/BashGuide/Arrays

Edit: I just want to add, arrays are certainly the way to go. Any time you have multiple related strings (i.e. lists of entries), you should start by storing them in an array, rather than a scalar variable. This way you can avoid having to break them up later.

Last edited by David the H.; 11-11-2011 at 03:00 PM. Reason: fixed formatting + minor rewording
 
3 members found this post helpful.
Old 11-12-2011, 03:28 AM   #7
Michael22Orr
LQ Newbie
 
Registered: Nov 2011
Posts: 2

Rep: Reputation: Disabled
Hello Negendar you can use this code, is this case you wont need to use arrays;

#!/bin/bash
ch1="a b c d"
ch2="w x y z"
i=0

IFS=" "
for ch in $ch1; do
echo ${ch1:$i:1} ${ch2:$i:1}
(( i+=2 ))
done
Thanks
ahh bra
 
Old 11-12-2011, 03:47 PM   #8
suicidaleggroll
LQ Guru
 
Registered: Nov 2010
Location: Colorado
Distribution: OpenSUSE, CentOS
Posts: 5,573

Rep: Reputation: 2142Reputation: 2142Reputation: 2142Reputation: 2142Reputation: 2142Reputation: 2142Reputation: 2142Reputation: 2142Reputation: 2142Reputation: 2142Reputation: 2142
Quote:
Originally Posted by Michael22Orr View Post
Hello Negendar you can use this code, is this case you wont need to use arrays;

#!/bin/bash
ch1="a b c d"
ch2="w x y z"
i=0

IFS=" "
for ch in $ch1; do
echo ${ch1:$i:1} ${ch2:$i:1}
(( i+=2 ))
done
Thanks
ahh bra
That will break as soon as the inputs are no longer a set of single characters with single character delimiters. In other words, it will break as soon as he tries to run it with anything other than the grossly simplified example in the OP.
 
Old 11-12-2011, 03:56 PM   #9
Juako
Member
 
Registered: Mar 2010
Posts: 202

Rep: Reputation: 84
Quote:
Originally Posted by suicidaleggroll View Post
That will break as soon as the inputs are no longer a set of single characters with single character delimiters. In other words, it will break as soon as he tries to run it with anything other than the grossly simplified example in the OP.
That's pretty much evident, but I don't see OP asking a generalized solution or indicating that inputs are going to be different. Perhaps he really wanted to work with that string?

@Michael22Orr:
How is your code different than what i posted? Just curious

Last edited by Juako; 11-12-2011 at 03:57 PM.
 
Old 11-13-2011, 04:54 AM   #10
David the H.
Bash Guru
 
Registered: Jun 2004
Location: Osaka, Japan
Distribution: Arch + Xfce
Posts: 6,852

Rep: Reputation: 2037Reputation: 2037Reputation: 2037Reputation: 2037Reputation: 2037Reputation: 2037Reputation: 2037Reputation: 2037Reputation: 2037Reputation: 2037Reputation: 2037
By the way, in bash at least, there's a more compact way to iterate through an array.

Code:
for i in "${!array1[@]}"; do
        echo "${array1[i]} : ${array2[i]}"
done
${!array[@]} outputs a list of all existing array indexes. This is especially useful with sparse arrays (arrays with missing elements) and associative arrays (which use strings as indexes).

So the above is all you need as long as array2 has exactly the same indexes as array1.
 
1 members found this post helpful.
Old 03-08-2017, 05:54 PM   #11
fshields
LQ Newbie
 
Registered: Mar 2017
Posts: 1

Rep: Reputation: Disabled
Try using delimited values

The method that I use is a little more old fashioned, but I think it is clearer to understand and is portable across shells...

Just pass the 'for' loop a list of delimited values and then split them up inside your loop.
Code:
for KeyValPair in 'a,w' 'b,x' 'c,y' 'd,z'
do
  i=`echo "$KeyValPair" | cut -d',' -f1`
  j=`echo "$KeyValPair" | cut -d',' -f2`
  echo $i:$j
done
Here's another example:
Code:
for NamePair in 'John,Smith' 'Jane,Doe' 'Betty,Doe-Smith' 'Madonna,'
do
  FirstName=`echo "$NamePair" | cut -d',' -f1`
  LastName=`echo "$NamePair" | cut -d',' -f2`
  echo "First: $FirstName  Last: $LastName"
done
You must use a delimiter that should never appear in your data. If I had used a dash delimiter, then item #3 would have been 'Betty-Doe-Smith' resulting in a LastName of just 'Doe', which is incorrect. If you use single quotes for each data pair (or triplet, or quaqruplet, etc.) then you can use more exotic characters like a pipe symbol: 'Betty|Doe-Smith'

Note that this technique allows you to have "null" items as in the example for Madonna (who does not have a last name). Just make sure that still include the delimiters.
 
Old 05-22-2017, 02:21 PM   #12
NewUnixBee
LQ Newbie
 
Registered: May 2017
Posts: 1

Rep: Reputation: Disabled
Quote:
Originally Posted by fshields View Post
The method that I use is a little more old fashioned, but I think it is clearer to understand and is portable across shells...

Just pass the 'for' loop a list of delimited values and then split them up inside your loop.
Code:
for KeyValPair in 'a,w' 'b,x' 'c,y' 'd,z'
do
  i=`echo "$KeyValPair" | cut -d',' -f1`
  j=`echo "$KeyValPair" | cut -d',' -f2`
  echo $i:$j
done
Here's another example:
Code:
for NamePair in 'John,Smith' 'Jane,Doe' 'Betty,Doe-Smith' 'Madonna,'
do
  FirstName=`echo "$NamePair" | cut -d',' -f1`
  LastName=`echo "$NamePair" | cut -d',' -f2`
  echo "First: $FirstName  Last: $LastName"
done
You must use a delimiter that should never appear in your data. If I had used a dash delimiter, then item #3 would have been 'Betty-Doe-Smith' resulting in a LastName of just 'Doe', which is incorrect. If you use single quotes for each data pair (or triplet, or quaqruplet, etc.) then you can use more exotic characters like a pipe symbol: 'Betty|Doe-Smith'

Note that this technique allows you to have "null" items as in the example for Madonna (who does not have a last name). Just make sure that still include the delimiters.
Can we use the same logic for a pair of dates?
 
  


Reply


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
Shell script - displaying multiple variables mobarger Linux - General 6 10-19-2016 09:56 PM
shell variables becoming zero outside the loop cool244 Programming 4 05-20-2006 04:33 PM
shell variables losing value outside while loop cool244 Programming 1 05-19-2006 11:04 AM
shell script - while loop with multiple conditions ronsha Programming 13 12-10-2005 05:08 PM

LinuxQuestions.org > Forums > Linux Forums > Linux - Newbie

All times are GMT -5. The time now is 10:20 AM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration