Bash is a popular shell scripting language used in Linux and Unix operating systems. It provides a rich set of commands and features that make it easy to automate repetitive tasks. The ‘readarray’ is one of the most helpful commands in Bash. With this command, lines from a file can be read into a 2D array. In this post, we’ll go over how to read lines from a file into a 2D array using Bash’s “readarray” command.
Using ‘readarray’ in Bash
The ‘readarray’ command reads lines from a file or standard input and assigns them to an array. The syntax for using ‘readarray’ is as follows:
The options available for the ‘readarray’ command are:
‘-d DELIM’: Sets the delimiter to use when splitting lines into array elements and by default, the delimiter is a newline character.
‘-n COUNT’: Specifies the maximum number of lines to read into the array.
‘-O ORIGIN’: Sets the starting index of the array.
‘-s COUNT’: Specifies the number of lines to skip before reading into the array.
‘-t’: Removes the trailing newline character from each line read into the array.
Here’s an example of using ‘readarray’ to read lines from a file into a 2D array and for that I have created a testfile.txt whose contents are:
4 5 6
7 8 9
So here is the complete bash script that demonstrates the use of ‘readarray’ command:
# Read lines from a file into the array
readarray -t lines < testfile.txt
# Declare a 2D array with 3 rows and 3 columns
declare -A array
# Iterate over the lines and split each line into elements
for i in "${!lines[@]}"; do
IFS=' ' read -r -a elements <<< "${lines[i]}"
for j in "${!elements[@]}"; do
if [[ -n "${elements[j]}" ]]; then
array[$i,$j]=${elements[j]}
fi
done
done
# Print the array
for ((i=0;i<3;i++)); do
for ((j=0;j<3;j++)); do
echo -n "${array[$i,$j]} "
done
echo
done
Here first I have declared a 2D array called ‘array’ and then used the ‘readarray’ command to read lines from a file called ‘testfile.txt’ into the ‘lines’ array. Next, the code iterates over the ‘lines’ array and split each line into elements using the ‘IFS’ and ‘read’ commands.
After that, it stores the elements in the 2D array ‘array’ and then uses the read command to split each line into elements. Now each element is assigned to the corresponding element in the ‘array’ array and finally, the contents of the ‘array’ array using nested for loops are printed.
Conclusion
The ‘readarray’ command makes it easy to manipulate large amounts of data in Bash scripts. By following the examples provided in this article, you can start using ‘readarray’ in your own Bash scripts to read lines from files and process them into 2D arrays.