Quantcast
Channel: UNIX and Linux Forums
Viewing all articles
Browse latest Browse all 16232

How to print elements between letters bash script?

$
0
0
Hello to all,

May somebody help me to fix my bash code below, I'd like to do it only using loops and if statements is possible.

I the content of the arrays are represented by the following 2 strings, where each character is an element inside the array.

String for case 1:
Code:

81UV78UV183UV89800
String for case 2:
Code:

8U1UVV78UUV18UU3UV89800
The strings are separated by "U" followed by "V", this is "UV", but sometimes U or V appears alone (not in sequence UV). I want to print the elements between UV concatenated in a single string.

For String 1 the array is 1rst one and the output would be:
Code:

81
78
183
89800

and I'm only getting 81, 78 and 89800.

for String 2 the array is 2nd one "commented" and the output would be:
Code:

8U1
V78U
18UU3
89800

and I'm only getting 8, 78 and 18.

The code I have so far is:
Code:

#!/bin/bash
 
#String 1 (81UV78UV183UV89800) represents content of  this array
a[0]=8;a[1]=1;a[2]=U;a[3]=V;a[4]=7;a[5]=8;a[6]=U;
a[7]=V;a[8]=1;a[9]=8;a[10]=3;a[11]=U;a[12]=V;
a[13]=8;a[14]=9;a[15]=8;a[16]=0;a[17]=0;
 
#String 2 (8U1UVV78UUV18UU3UV89800) represents content of  this array
#a[0]=8;a[1]=U;a[2]=1;a[3]=U;a[4]=V;a[5]=V;a[6]=7;a[7]=8;
#a[8]=U;a[9]=U;a[10]=V;a[11]=1;a[12]=8;a[13]=U;a[14]=U;a[15]=3;a[16]=U;
#a[17]=V;a[18]=8;a[19]=9;a[20]=8;a[21]=0;a[22]=0;
 
for (( i=0; i<${#a[@]}; i++))
do
 if [ "${a[$i]}" == "U" ]; then
  c=1
 elif [ "${a[$i]}" == "V" ]; then
  c=0
  if (( ${#buff} > 0 )); then
  echo ${buff}
  buff=""
  fi
 elif (( c == 0 )); then
  buff=${buff}${a[$i]}
 fi
done

PS: The data is stored in arrays initially but I show you the way the data looks in a string for you to understand better. I'm using Cygwin.

Thanks in advance for any help.

Viewing all articles
Browse latest Browse all 16232

Trending Articles