Select / Print odd-even elements of an array


 
Thread Tools Search this Thread
Top Forums Shell Programming and Scripting Select / Print odd-even elements of an array
# 1  
Old 08-22-2016
Select / Print odd-even elements of an array

Hello experts,

I wish to print the contents of odd-even numbered indices of an array.

The problem statement is as follows :

1. The first line contains an integer, (the number of test cases).
2. Each line of the subsequent lines containing a string.

Example:

Code:
2
Haider
Bash


Explanation:

Code:
A[0]=H
A[1]=a
A[2]=i
A[3]=d
A[4]=e
A[5]=r


X[0]=B
X[1]=a
X[2]=s
X[3]=h


The expected output :

Hie adr :: The first elements are the even indexed elements are displayed followed by a space, followed by the odd indexed elements of array 1.
Bs ah :: The first elements are the even indexed elements are displayed followed by a space, followed by the odd indexed elements of array 2.

Code written so far :

Code:
read n
read -a arr1
read -a arr2

Could you please help.

Thanks,
Haider


Moderator's Comments:
Mod Comment Thanks for using code tags, but usually you don't have to put code tags inside code tags. I removed some to make it a bit more readable.

Last edited by zaxxon; 08-22-2016 at 02:59 AM..
# 2  
Old 08-22-2016
Hello H squared,

Following may help you in same.(tested with GNU awk).
Code:
awk '($0 ~ /[[:digit:]]/){print;next} ($0 ~ /[[:alpha:]]/){num=split($0, A,"");for(i=1;i<=num;i+=2){Q=Q?Q A[i]:A[i]};Q=Q OFS;for(i=2;i<=num;i+=2){Q=Q?Q A[i]:A[i]};print Q;Q=""}'  Input_file

Output will be as follows.
Code:
2
Hie adr
Bs ah

EDIT: Adding a non-one liner form of solution now.
Code:
awk '($0 ~ /[[:digit:]]/){
                                print;
                                next
                         }
     ($0 ~ /[[:alpha:]]/){
                                num=split($0, A,"");
                                for(i=1;i<=num;i+=2){
                                                        Q=Q?Q A[i]:A[i]
                                                    };
                                Q=Q OFS;
                                for(i=2;i<=num;i+=2){
                                                        Q=Q?Q A[i]:A[i]
                                                    };
                                print Q;
                                Q=""
                         }
    '   Input_file

EDIT2: Adding one more solution on same too.
Code:
awk '($0 ~ /[[:digit:]]/){print;next} ($0 ~ /[[:alpha:]]/){num=split($0, A,"");for(i=1;i<=num;i++){Q=i%2==0?(v1=v1?v1 A[i]:A[i]):(v2=v2?v2 A[i]:A[i])};print v2 OFS v1;v1=v2=""}'  Input_file

OR(non-one liner form of above solution)

awk '($0 ~ /[[:digit:]]/){
                                print;
                                next
                         }
     ($0 ~ /[[:alpha:]]/){
                                num=split($0, A,"");
                                for(i=1;i<=num;i++){
                                                        Q=i%2==0?(v1=v1?v1 A[i]:A[i]):(v2=v2?v2 A[i]:A[i])
                                                   };
                                print v2 OFS v1;
                                v1=v2=""
                         }
    '   Input_file

Output will be as follows.
Code:
2
Hie adr
Bs ah

Thanks,
R. Singh

Last edited by RavinderSingh13; 08-22-2016 at 03:31 AM.. Reason: Adding a non-one liner form of solution now. Added one more solution too now, to avoid 2 times loop running.
This User Gave Thanks to RavinderSingh13 For This Post:
# 3  
Old 08-22-2016
Try

Code:
[akshay@localhost tmp]$ cat f
2
Haider
Bash

Code:
[akshay@localhost tmp]$ awk '!/^[0-9]/{split($0,a,""); e=o="";for(i=1; i in a; i++) i%2?e=e a[i]:o=o a[i]; print e,o }' f
Hie adr
Bs ah

This User Gave Thanks to Akshay Hegde For This Post:
# 4  
Old 08-22-2016
Hi H squared,
That isn't the way arrays work. Reading an array creates elements based on field splitting; not arrays of individual characters. But, both recent versions of bash and 1993 or later versions of ksh support extensions to the standard providing simplified for loops and substring variable expansions that do what is needed here:
Code:
#!/bin/bash
{	read -r n
	printf 'Expecting to process %s lines...\n' "$n"
	while IFS= read -r text
	do	printf 'Processing text: "%s"\n' "$text"
		for((i = 0; i < ${#text}; i += 2))
		do	printf '%s' "${text:$i:1}"
		done
		printf ' '
		for((i = 1; i < ${#text}; i += 2))
		do	printf '%s' "${text:$i:1}"
		done
		echo
	done
} < file

which with the input you showed us in a file named file produces the output:
Code:
Expecting to process 2 lines..
Processing text: "Haider"
Hie adr
Processing text: "Bash"
Bs ah

This User Gave Thanks to Don Cragun For This Post:
# 5  
Old 08-22-2016
Code:
bash-3.2$ cat a.txt
Testing
Hello
What are you doing

bash-3.2$ awk 'BEGIN{FS=""}{for(i=1;i<=NF;i++)if(i%2){odd=odd$i}else{even=even$i}print odd,even;odd=even="";}' a.txt
Tsig etn
Hlo el
Wa r o on htaeyudig

Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

Help reading the array and sum of the array elements

Hi All, need help with reading the array and sum of the array elements. given an array of integers of size N . You need to print the sum of the elements in the array, keeping in mind that some of those integers may be quite large. Input Format The first line of the input consists of an... (1 Reply)
Discussion started by: nishantrefound
1 Replies

2. Shell Programming and Scripting

Random elements from array

Hi I wanted to print random elements from an array at bash shell I use the following code, but I always see first element getting printed #!/bin/bash c=1 expressions=(pink red white yellow purple) while ]; do echo "The value of RANDOM is $RANDOM" selectedexpression=${expressions}]};... (5 Replies)
Discussion started by: Priya Amaresh
5 Replies

3. UNIX for Dummies Questions & Answers

How to declare an array in UNIX and print the elements with tab delimits?

Hello, In a shell script, I want to declare an array and subsequently print the elements with tab delimits. My array has the following structure and arbitrary elements: myArray=('fgh' 'ijk' 'xyz' 'abc'); Next, I would like to print it with a '\n' at the end. Thanks for your input! ... (2 Replies)
Discussion started by: Gussifinknottle
2 Replies

4. Shell Programming and Scripting

Multiplication of array elements

Hi, I can't find out how to create correct code to get multiplication of each elements of array. Let's say I enter array into command line (2 3 4 5 6 8) and i need output 2*3*4*5*6*8=5760. I tried this one, but answer is 0. for i in $@; do mult=$((mult*i))done echo "mult: " $mult ... (4 Replies)
Discussion started by: rimasbimas
4 Replies

5. Shell Programming and Scripting

Grouping array elements - possible?

I have a script which takes backup of some configuration files on my server. It does that by using an array which contains the complete path to the files to backup. It copys the files to a pre defined dir. Each "program" has it's own folder, ex. apache.conf is being copied to /predefined... (7 Replies)
Discussion started by: dnn
7 Replies

6. Shell Programming and Scripting

Print arguments using array elements not working?

Hey guys, I'm new to shell scripting and I'm trying to write a script that takes user input and copies the specified columns from a data file to a new one. In order to account for the possibility of a variable number of columns to copy I wrote a loop that encodes the user's choices in an array... (16 Replies)
Discussion started by: shaner
16 Replies

7. Shell Programming and Scripting

Removing elements from an array

Hi I have two arrays : @arcb= (450,625,720,645); @arca=(625,645); I need to remove the elements of @arca from elements of @arcb so that the content of @arcb will be (450,720). Can anyone sugget me how to perform this operation? The code I have used is this : my @arcb=... (3 Replies)
Discussion started by: rkrish
3 Replies

8. Shell Programming and Scripting

How can I print array elements as different columns in bash?

Hi Guys, I have an array which has numbers including blanks as follows: 1 26 66 4.77 -0.58 88 99 11 12 333 I want to print a group of three elements as a different column in a file as follows:(including blanks where there is missing elements) for.e.g. array element #7... (4 Replies)
Discussion started by: npatwardhan
4 Replies

9. Shell Programming and Scripting

Accessing array elements

Hi, My doubt is how to access array elements.. Situation is as below: #!/bin/ksh set -x typeset -i x=0 typeset -i y=0 typeset -i BID=0 typeset -i count=0 while ] ; do x=`expr $x + 1`; hwmgr show scsi > scsi.tmp while read line; do set... (1 Reply)
Discussion started by: mansa
1 Replies

10. UNIX for Dummies Questions & Answers

Deleting Array Elements

Hi, I am writing a BASH shell script. I have an array that will contain IN ANY ORDER the following elements: DAY 8D MO NS. I would like to erase the element DAY, but since the order of the elements in the array are random, I will not know which element # DAY is (ie it's not as simple as... (3 Replies)
Discussion started by: msb65
3 Replies
Login or Register to Ask a Question