mohangraj
mohangraj

Reputation: 11104

Space and Newline in Array(Shell script)

How to store space and Newline in array. Consider the following is my file.

a.txt:

this is file a.txt
for testing
and for checking

Now, I want to store each and every character in the file in each element of the array. Like 't' in arr[0], 'h' in arr[1], 'i' in arr[2], 's' in arr[3] and ' '(space) in arr[4] respectively. And If I print the content of array like ${a[*]}, the output is to be exact file content. So, is there any way to store space and newline in array.

Upvotes: 1

Views: 336

Answers (1)

anubhava
anubhava

Reputation: 786091

You can use:

arr=()

while IFS= read -d '' -r -n1 c; do
    arr+=("$c")
done < file
  • read -n1 will make this loop read the input character by character.
  • -d '' will make delimiter as null instead of newline
  • IFS= is needed to read leading or trailing spaces in each line.

Verify:

printf "%s" "${arr[@]}"
this is file a.txt
for testing
and for checking

Upvotes: 1

Related Questions