Autosave: 2023-02-26 11:56:30

This commit is contained in:
thomasabishop 2023-02-26 11:56:30 +00:00
parent e8b832f160
commit a86b245f78
6 changed files with 100 additions and 41 deletions

View file

@ -26,6 +26,10 @@ blockquote {
background: #637d7510;
}
::selection {
background: #1d4125; /* WebKit/Blink Browsers */
}
table {
table-layout: fixed;
width: 100%;

View file

@ -1,12 +0,0 @@
---
categories:
- Programming Languages
tags:
- shell
---
# Read an input file line by line
```bash
# Add snippet here
```

View file

@ -6,26 +6,7 @@ tags:
- data-structures
---
# Lists and arrays in Bash
## List variables
When we use the term **list** in bash, we are not actually referring to a specific type of data structure. Instead a **list variable** is really just a normal variable wrapped in quote marks that has strings separated by spaces. Despite the fact that this is not an actual iterative data structure, we are still able to loop through variables of this type.
```bash
A_STR_LIST="cat dog hamster"
AN_INT_LIST="1 2 3"
```
To iterate through a list variable, we can use a for loop:
```bash
for ele in $A_STR_LIST; do
echo $ele
done
```
## Arrays
# Arrays in Bash
We define an array as follows:
@ -39,17 +20,17 @@ We can also explicitly define an array using `declare` :
declare -a words=("element1" "element2" "element3")
```
### Index notation
## Index notation
We access specific array elements by their index using the same braces style we use with variables:
```bash
echo ${words[2]}
echo "${words[2]}"
# element3
```
### Iterating through arrays
## Iterating through arrays
```bash
for i in "${words[@]}"
@ -62,9 +43,9 @@ done
Note that `@` here is a special symbol standing for all the members of the `words` array.
### Sorting arrays
## Sorting arrays
#### Sorting an integer array highests to lowest
### Sorting an integer array highests to lowest
```bash
sorted_array=($(echo "${array[@]}" | tr " " "\n" | sort -nr))
@ -74,6 +55,20 @@ Where `array` is the name of the original array. The sorted array will be stored
The `sort` command sorts the input in reverse numerical order (`-n` for numerical sort and `-r` for reverse sort). The `tr` command is used to convert the spaces in the array to newline characters so that each element is sorted on a separate line.
## Pushing, appending to an array
We use the `+=` shorthand to add elements to a preexisting array:
```bash
preExistingArray=(1 2 3)
preExistingArray+=(4)
echo preExistingArray
# 1 2 3 4
```
> Note that we have to put the item we want to addend within array brackets
## Looping through file system
The following script loops through all files in a directory that begin with `l` and which are of the bash file type (`.sh`) :
@ -94,3 +89,22 @@ declare -A rock=(["win"]="scissors" ["lose"]="paper")
```
We would then individuate a value with `"${rock[win]}"`
## Lists as implicit string arrays
When we use the term **list** in bash, we are not actually referring to a specific type of data structure. Instead a **list variable** is really just a normal variable wrapped in quote marks that has strings separated by spaces. Despite the fact that this is not an actual iterative data structure, we are still able to loop through variables of this type.
```bash
A_STR_LIST="cat dog hamster"
AN_INT_LIST="1 2 3"
```
To iterate through a list variable, we can use a for loop:
```bash
for ele in $A_STR_LIST; do
echo $ele
done
```
We are leveraging this aspect of Bash when we [loop through each character in a string](/Programming_Languages/Shell/Strings_in_bash.md#loop-through-each-character-in-a-string).

View file

@ -5,7 +5,7 @@ tags:
- shell
---
# `read`
# read
The primary use of `read` is to capture user input from `stdin`. It is also often used frequently to parse strings or files that are redirected to it (with `<` and `<<`) or piped to it. In each case, what is read is stored as a variable.
@ -41,7 +41,7 @@ while read var; do
done < './input-file.txt
```
## `$REPLY`
## $REPLY
If you do not assign a variable name to store the value that `read` reads a default (`$REPLY`) is applied. You can reference this value in your code.

View file

@ -7,7 +7,7 @@ tags:
# Splitting input into an array
## `readarray`
## readarray
`readarray` makes it really easy to split input into an array based on new lines.
Say we have this file as input:
@ -48,7 +48,7 @@ is
Add more: https://linuxhint.com/split-string-array-bash/
## `read`
## read
For different delimiters we have to use `read`, combined with `IFS` the **Internal Field Separator**.
@ -62,3 +62,40 @@ something, something else, something more
```bash
IFS=',' read -a arr < ./comma_inputs.txt
```
> We use the `-a` flag to signal that we want each item read returned as an element in an array
## mapfile
We can use `mapfile` to read the lines of a input file in set segments.
For the following file:
```
line one
line two
line three
line four
```
We could generate the following output:
```
-----SNIP-----
line one
line two
-----SNIP-----
line three
line four
```
With:
```bash
while mapfile -t -n 2 ary && ((${#ary[@]})); do
printf '%s\n' "${ary[@]}"
printf -- '--- SNIP ---\n'
done < $testInput
```
So, while there are input lines, map each line into an array and return it in groups of 2.

View file

@ -71,3 +71,19 @@ The extended test supports the standard `test` comparisons and adds other featur
```
[[ -d ~ || -a /bin/mash ]]; echo $?
```
## Further examples
**Test if a character exists in two strings**
```bash
string1="hello"
string2="world"
char="l"
if [[ "$string1" == *"$char"* ]] && [[ "$string2" == *"$char"* ]]; then
echo "Character '$char' exists in both strings."
else
echo "Character '$char' does not exist in both strings."
fi
```