Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 将带有空格的输入作为单个元素放入bash中的数组中_Arrays_Bash_Unix - Fatal编程技术网

Arrays 将带有空格的输入作为单个元素放入bash中的数组中

Arrays 将带有空格的输入作为单个元素放入bash中的数组中,arrays,bash,unix,Arrays,Bash,Unix,我有一个文件,使用cut命令从中提取前三列,并将它们写入数组 当我检查数组的长度时,它给了我四个。我需要数组只有3个元素 aaa|111|ADAM|1222|aauu aaa|222|MIKE ALLEN|5678|gggg aaa|333|JOE|1222|eeeee target=($(cut -d '|' -f1-3 sample_file2.txt| sort -u )) 我认为它将空间作为数组元素的分隔符 aaa|111|ADAM|1222|aauu aaa|222|MIKE

我有一个文件,使用
cut
命令从中提取前三列,并将它们写入数组

当我检查数组的长度时,它给了我四个。我需要数组只有3个元素

aaa|111|ADAM|1222|aauu

aaa|222|MIKE ALLEN|5678|gggg
aaa|333|JOE|1222|eeeee

target=($(cut -d '|' -f1-3 sample_file2.txt| sort -u ))
我认为它将空间作为数组元素的分隔符

aaa|111|ADAM|1222|aauu

aaa|222|MIKE ALLEN|5678|gggg
aaa|333|JOE|1222|eeeee

target=($(cut -d '|' -f1-3 sample_file2.txt| sort -u ))

bash
4或更高版本中,将
readarray
与进程替换一起使用以填充数组。实际上,您的代码无法区分将输出中的每一行分隔开的空格与“Mike Allen”中出现的空格。
readarray
命令将输入的每一行放入一个单独的数组元素中

readarray -t target < <(cut -d '|' -f1-3 sample_file2.txt| sort -u)

或者,使用臭名昭著的
eval

eval target=($(cut -sd '|' -f1-3 sample_file2.txt | sort -u | \
               xargs  -d\\n printf "'%s'\n"))
这应该起作用:

IFS=$'\n' target=($(cut -d '|' -f1-3 sample_file2.txt| sort -u ))
例如:

#!/bin/bash
IFS=$'\n' target=($(cut -d '|' -f1-3 sample_file2.txt| sort -u ))
echo ${#target[@]}
echo "${target[1]}"
输出:

3
aaa|222|MIKE ALLEN

是否需要将每行的前三个字段作为单个数组元素?请看是的,我需要前三个字段作为arrayHi中的单个元素,我们可以在bash中使用readarray吗?我在尝试上述命令时出错。您确实需要使用
bash
4或更高版本。否则,你需要使用一些更混乱的东西。我的描述有一个拼写错误。循环版本应该适用于3.x系列中的任何东西。