Awk: Storing string in array(triangular form)


 
Thread Tools Search this Thread
Top Forums Shell Programming and Scripting Awk: Storing string in array(triangular form)
# 1  
Old 01-05-2016
Awk: Storing string in array(triangular form)

I have a string like below. Now i want to split this string like below and put the value in the array using awk. I am able to do it using bash but getting no clue for doing it in awk

O/P
Code:
A[0]=0  
A[1]=01  
A[2]=014  
A[3]=0143  
A[4]=01438  
A[5]=014387  
A[6]=0143876  
A[7]=01438765  
A[8]=014387650

Bash code
Code:
triangle_split() {
  _len=1
  while [ "$_len" -le "${#1}" ]; do
    printf '%.*s\n' "$_len" "$1"
    : "$((_len+=1))"
  done
}

IFS='
'
A=($(triangle_split 014387650))
printf '%s\n' "${A[@]}"

# 2  
Old 01-05-2016
Hello siramitsharma,

If I understood your requirement correctly, could you please try following and let me know if this helps you.
Code:
echo "014387650" | awk '{n=split($0, A,"");if(A[1]==0){e=1};for(i=1;i<=n;i++){while(q<=i){W=W?W A[q]:A[q];q++};if(e && i>1){W=0 W};print "A[" i-1 "]=" W;W="";q=1}}'

Output will be as follows.
Code:
A[0]=0
A[1]=01
A[2]=014
A[3]=0143
A[4]=01438
A[5]=014387
A[6]=0143876
A[7]=01438765
A[8]=014387650

Thanks,
R. Singh
This User Gave Thanks to RavinderSingh13 For This Post:
# 3  
Old 01-05-2016
Thanks ravinder, but i need to store the same in array which is being mentioned in my bash code & not explicitly printing like the one you mentioned,i.e, if i access A[0] then i should get value 0, if i access A[1] then i should get value 01 & so on. Can you please advice accordingly?
# 4  
Old 01-05-2016
Hello siramitsharma,

Your question's answer lies in my previous post itself, split function used for same only, Here I am taking an array named A in split and giving delimiter as "" means NULL, so it's syntax is split(Line, array_name,delimiter). So once elements store into array A you could access them as follows for an example.
Code:
 echo "014387650" | awk '{split($0, A,"");print A[1]}'
 0

We need to note here split created array's element count from 1 unlike the usual arrays where element count starts from 0. Let me know if you have any queries here.

Thanks,
R. Singh
# 5  
Old 01-05-2016
Thanks Ravinder, i have done some modifications and i am able to achieve what i wanted. Btw i have single query for below code logic, can you please throw some light on this.

Code:
if(A[1]==0)
{
e=1
}

# 6  
Old 01-05-2016
What you are trying to do isn't really clear yet. Perhaps this will give you an idea of how to do some of the things one could guess might do what you're trying to do:
Code:
#!/bin/bash
# If you're trying to produce the output you say your bash script prints (even
# though that is not the output your script produces):
echo 014387650 |
awk '{for(i = 1; i <= length($1); i++) printf("A[%d]=%.*s\n", i - 1, i, $1) }'

# If you're trying to change your existing function to use awk (and print what
# your current script prints):
triangle_split() {
	echo "$1" |
	awk '{for(i = 1; i <= length($1); i++) printf("%.*s\n", i, $1)}'
}
A=($(triangle_split 014387650))
printf '%s\n' "${A[@]}"

# If you're trying to create an array in awk instead of a bash array:
echo 014387650 |
awk '{	# Create array:
	for(i = 0; i < length($1); i++)
		A[i] = substr($1, 1, i + 1)
	# Do whatever you want with the array (in this case, print it)...
	for(i = 0; i < length($1); i++)
		printf("A[%d]=%s\n", i, A[i])
}'

Note that using awk instead of shell built-ins as a replacement for your current shell function will be a LOT slower. The output from the above script is:
Code:
A[0]=0
A[1]=01
A[2]=014
A[3]=0143
A[4]=01438
A[5]=014387
A[6]=0143876
A[7]=01438765
A[8]=014387650
0
01
014
0143
01438
014387
0143876
01438765
014387650
A[0]=0
A[1]=01
A[2]=014
A[3]=0143
A[4]=01438
A[5]=014387
A[6]=0143876
A[7]=01438765
A[8]=014387650

If you want to try this on a Solaris/SunOS system, change awk in all of these cases to /usr/xpg4/bin/awk or nawk.
# 7  
Old 01-05-2016
Quote:
Originally Posted by siramitsharma
Thanks ravinder, but i need to store the same in array which is being mentioned in my bash code & not explicitly printing like the one you mentioned,i.e, if i access A[0] then i should get value 0, if i access A[1] then i should get value 01 & so on. Can you please advice accordingly?
Hello siramitsharma,

Following is the complete explanation for post above, which may help you to understand the code.
Code:
echo "014387650"          ####### using echo to print the string provided by OP in POST.
|                         ####### Using | to send previous command's standard output as standard input to next command.
awk '{n=split($0, A,"");  ####### using split function here to split the elements of line into an array named A and whose delimiter is NULL. Also taking the count of elements in array A into variable named n.
if(A[1]==0){              ####### Checking here if very first element of array or very first digit of line is 0, if it is 0 then later when we append all the elements it is not showing them in that variable like 01, 014 etc it shows rather 1, 14 so only checking it here itself.
e=1};                     ####### Setting variable named e's value to 1 here.
for(i=1;i<=n;i++){        ####### starting a loop for which will run till the value of variable n.
while(q<=i){              ####### Starting a while loop which will till the value of q is equal to variable's i.
W=W?W A[q]:A[q];q++};     ####### Here I am taking values into variable named W, so each time while loop will run it will append values into variable W, then incrementing the value of q to make loop running correctly.
if(e && i>1){             ####### Now checking value of variable named e's value and if it is 1 it means first element of line is 0 and i's value should be greater than 1.
W=0 W};                   ####### If above condition is TRUE then make variable W's value to 0 W.
print "A[" i-1 "]=" W;    ####### printing value of variable W now.
W="";q=1}}'               ####### Nullifying the variable named W and setting q's value to 1 now.

Thanks,
R. Singh
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. UNIX for Beginners Questions & Answers

awk Associative Array and/or Referring to Field by String (Nonconstant String Value)

I will start with an example of what I'm trying to do and then describe how I am approaching the issue. File PS028,005 Lexeme HRS # M # PhraseType 1(1:1) 7(7) PhraseLab 501 503 ClauseType ZYq0 PS028,005 Lexeme W # L> # BNH # M #... (17 Replies)
Discussion started by: jvoot
17 Replies

2. Shell Programming and Scripting

Storing two dimensional array for postprocessing

Hi Community, Would love to get some quick help on below requirement. I am trying to process mpstat output from multiple blades of my server I would like to assign this the output to an array and then use it for post processing. How can I use a two dimensional array and assign these value ... (23 Replies)
Discussion started by: sshark
23 Replies

3. Shell Programming and Scripting

Storing command output in an array

Hi, I want keep/save one command's output in an array and later want to iterate over the array one by one for some processing. instead of doing like below- for str in `cat /etc/passwd | awk -F: '$3 >100 {print $1}' | uniq` want to store- my_array = `cat /etc/passwd | awk -F: '$3 >100 {print... (4 Replies)
Discussion started by: sanzee007
4 Replies

4. Programming

C; storing strings in an array

I am trying to get userinput from stdin and store the lines in an array. If i do this: using a char **list to store strings allocate memory to it #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv) { char *prog = argv; char **linelist; int... (5 Replies)
Discussion started by: tornow
5 Replies

5. Shell Programming and Scripting

awk - from arrays to lower triangular matrix

Hi, I have to reshape some ascii files. I have many ascii files that have collapsed the lower triangular of my matrix into row. I simply want to convert them back to the proper matrix form. So, my current data looks like this: 11 21 22 31 32 33 41 42 43 44 ... This is five columns of... (2 Replies)
Discussion started by: Viko Haestner
2 Replies

6. Shell Programming and Scripting

fetching values using awk and storing into array

hi all I am using awk utility to parse the file and fetching two different vaues from two different record of a record set. I am able to see the result, now i want to store the result and perform some check of each values form database to mark valid and invalid. could you please help me... (3 Replies)
Discussion started by: singhald
3 Replies

7. Shell Programming and Scripting

storing values in a list or array

i have a file called file.txt having the following entries. 2321 2311 2313 4213 i wnat to store these values in a list and i want to iterate the list using loop and store it in another list (1 Reply)
Discussion started by: KiranKumarKarre
1 Replies

8. Shell Programming and Scripting

storing records in awk array

hi i have a file as follows: 1 2 3 4 5 6 i want to store all these numbers in an array using awk.. so far i have: awk '{for(i=1;i<=NR;i++) {a=$1}} END {for(i=1;i<=NR;i++) {printf("%1.11f",a)}}' 1.csv > test however, i am getting all values as zero in the "test" file..... (3 Replies)
Discussion started by: npatwardhan
3 Replies

9. Shell Programming and Scripting

storing variables in array.Please help

Hi All, I need some help with arrays. I need to take input from the user for hostname, username and password until he enters .(dot) or any other character and store the values in the variable array. I would further connect to the hostname using username and passwd and copy files from server to... (7 Replies)
Discussion started by: nua7
7 Replies

10. UNIX for Dummies Questions & Answers

Storing pointer array in C

All .. I am having a pointer array . And trying to store the addess into that pointer array . please see below the problem i faced code: int cnt1; char *t_array; char *f_array; for(cnt1=0; cnt1<1000; cnt1++) { t_array =... (1 Reply)
Discussion started by: arunkumar_mca
1 Replies
Login or Register to Ask a Question