dylanaraps / pure-sh-bible

📖 A collection of pure POSIX sh alternatives to external processes.
MIT License
6.45k stars 281 forks source link

Define and use 2-dimensional arrays? #15

Open LinArcX opened 4 years ago

LinArcX commented 4 years ago

I'm curious to know is there any way to this in pure POSIX shell?

spiralofhope commented 4 years ago

I can almost wrap my brain around it.

I wonder if iterating through a heredoc string could do it.

Getting rows is easy for a list. Then iterate through a row with a split being some defined IFS.

So the function to fetch from it would be something like:

# TODO
get_content_from_array(){}

array_text_to_check="the first row
second line here
some additional text"

# I'd make a simple function which can be re-used independently of row/column, like:

row_match=$( 
  get_content_from_array  \
  "$array_text_to_check"  \
  '\n'  \
  2  \
)

column_match=$( 
  get_content_from_array  \
  "$row"  \
  ' '  \
  3  \
)

echo $column_match
# =>
# here

The remaining problems would be:

spiralofhope commented 4 years ago

I grew interested in this problem for another project of mine. This will fetch any given line and character in a list:

https://github.com/spiralofhope/shell-random/blob/master/live/sh/scripts/array-fetch-character.sh

spiralofhope commented 4 years ago

Also, given that I can replace seq with examples from this bible, I also implemented range output:

https://github.com/spiralofhope/shell-random/blob/master/live/sh/scripts/string-fetch-character-range.sh

Be aware that this script refers to other scripts of mine, so you'll have to copy-paste a bit to make it work as one single standalone script.


Also, also, it would be possible to output a rectangle of characters. I'd implement a sort of list-fetch-row-range.sh, then:

I can see it in my head..


Also.. and it's crazy, but since a pure sh implementation of seq can be made to skip numbers in any number of ways, this functionality could get every x rows, or columns, fetching stripes or a checkerboard of characters for example. It could even be made very selective, skipping over whole rows whose first character is 'x', etc.