Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Reading into 2d array without a delimiter

Status
Not open for further replies.

Mrk200

Technical User
Feb 15, 2004
3
US
Hello, I'm having trouble trying to read in input such as this:

3 4
abcd
efgh
ijkl

And then placing it into a 2D array. The 3 and 4 are the number of rows and columns. Any ideas on how to go about doing this?
 
Well, I got it to read in just the 2D array part, but how do I read in the number of rows and columns, and then remove that from the input so that the program doesn't think that they are part of the array?
 
This shows you how to read the file into a 1D array of strings. If you want to chop each line up into individual characters using say substr(), then that should be easy to do.

Code:
#!/bin/awk -f
{
  if ( FNR == 1 ) {
    # first record contains the dimensions
    rows = $1
    cols = $2
  } else {
    # all other lines are the information
    data[FNR-1] = $0
  }
}

END {
  print "Dimensions are", rows, cols
  print "Letter at[2][3] is", substr(data[2],3,1)
}
Save as prog.awk, then invoke with
Code:
awk -f prog.awk file.txt

--
 
The following awk script read the input file and creates an two dimensional array.
[tt]
awk '
NR==1 {
rows = $1;
cols = $2;
next;
}
{
if (++row_index > rows) exit;
for (col_index=1; col_index<=cols; col_index++)
array2[row_index, col_index] = substr($0,col_index,1);
}
END {
for (row_index=1; row_index<=rows; row_index++) {
Out = &quot;Rows &quot; row_index &quot;: &quot;;
for (col_index =1; col_index<=cols; col_index++) {
Out = Out array2[row_index,col_index] &quot;, &quot;;
}
print substr(Out, 1, length(Out)-2);
}
}
' input_file
[/tt]
With your datas, the result is :
[tt]
Rows 1: a, b, c, d
Rows 2: e, f, g, h
Rows 3: i, j, k, l
[/tt]

Jean Pierre.
 
Thanks a bunch guys, it's working.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top