简体   繁体   English

如何在shell脚本中编写忽略空格的数组?

[英]How to write an array ignoring space characters in shell scripting?

I have a text file which consists of say ..following information say test.text : 我有一个文本文件,其中包含说..跟随信息说test.text

an
apple of 
one's eye

I want to read these lines in an array using shell scripting by doing a cat test.text. 我想通过执行cat test.text,使用shell脚本读取数组中的这些行。 I have tried using a=(`cat test.text`) , but that doesn't work as it considers space as a delimiter. 我已经尝试过使用a=(`cat test.text`) ,但是由于将空间视为定界符而无法正常工作。 I need the values as a[0]=an , a[1]=apple of , a[2]=one's eye . 我需要a[0]=ana[1]=apple ofa[2]=one's eye I don't want to use IFS . 我不想使用IFS Need help, thanks in advance..!! 需要帮助,在此先感谢..!

In bash 4 or later bash 4或更高版本中

readarray a < test.text

This will include an empty element for each blank line, so you might want to remove the empty lines from the input file first. 这将为每个空白行包含一个空元素,因此您可能需要首先从输入文件中删除这些空行。

In earlier versions, you'll need to build the array manually. 在早期版本中,您需要手动构建阵列。

a=()
while read; do a+=("$REPLY"); done < test.text

One of various options you have is to use read with . 您拥有的多种选择之一是将read一起使用。 Set IFS to the newline and line separator to NUL IFS设置为换行符并将行分隔符设置为NUL

IFS=$'\n' read -d $'\0' -a a < test.txt

Plain sh 普通sh

IFS='
'
set -- $(< test.txt)
unset IFS
echo "$1"
echo "$2"
echo "$@"

bash

IFS=$'\n' a=($(< test.txt))
echo "${a[0]}"
echo "${a[1]}"
echo "${a[@]}"

I'm inclined to say these are the best of the available solutions because they do not involve looping. 我倾向于说这些是现有解决方案中最好的,因为它们不涉及循环。

Let's say: 比方说:

cat file
an

apple of

one's eye

Use this while loop: 使用以下while循环:

arr=()
while read -r l; do
    [[ -n "$l" ]] && arr+=("$l")
done < file

TEST 测试

set | grep arr
arr=([0]="an" [1]="apple of" [2]="one's eye")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM