[英]Space and Newline in Array(Shell script)
How to store space and Newline in array. 如何在数组中存储空间和换行符。 Consider the following is my file.
考虑以下是我的文件。
a.txt: 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.
分别类似于arr [0]中的“ t”,arr [1]中的“ h”,arr [2]中的“ i”,arr [3]中的“ s”和arr [4]中的“'(space)”。 And If I print the content of array like ${a[*]}, the output is to be exact file content.
而且,如果我打印$ {a [*]}之类的数组内容,则输出将是准确的文件内容。 So, is there any way to store space and newline in array.
因此,有什么方法可以在数组中存储空间和换行符。
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. read -n1
将使此循环逐字符读取输入的字符。 -d ''
will make delimiter as null instead of newline -d ''
将分隔符设置为null而不是换行符 IFS=
is needed to read leading or trailing spaces in each line. IFS=
才能读取每行中的前导或尾随空格。 Verify: 校验:
printf "%s" "${arr[@]}"
this is file a.txt
for testing
and for checking
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.