[英]Shell Bash - Split Multilne String into Array
I am trying to get an Array that contains each string line as an element... 我正在尝试获取一个包含每个字符串行作为元素的数组...
stringy=$(ls -l | awk '{print$3,$6,$7,$8,$9}'| grep "$USER")
declare -a myarray=()
IFS="\n" read myarray <<< "$stringy"
echo "${myarray[0]}"
echo "${myarray[1]}"
echo "${myarray[2]}"
for line in "${myarray[@]}"; do
echo "$line"
done
The String looks something like this: 字符串看起来像这样:
brunor Nov 17 17:38 22735
brunor Nov 17 15:38 5391
brunor Nov 17 15:38 5405
brunor Nov 17 15:38 5444
(...) (......)
the code outputs just the first element (0) even for the loop: 该代码即使循环也仅输出第一个元素(0):
>brunor Nov 17 17:38 22735
>
>
>brunor Nov 17 17:38 22735
The primary issue is that you're reading myarray
as a regular variable, not as an array. 主要问题是您将
myarray
作为常规变量而不是数组读取。 Use readarray
instead: 使用
readarray
代替:
readarray -t myarray <<< "$stringy"
Other issues include: 其他问题包括:
IFS
is being set to the letter "n" and a backslash, not a linefeed IFS
设置为字母“ n”和反斜杠,而不是换行符 read
defaults to reading a single line regardless of IFS
read
默认为读取单行,而不考虑IFS
echo
is a bad way to check the contents of variables because it's ambiguous ( declare -p myarray
would have immediately shown the problem) echo
是检查变量内容的不好方法,因为它模棱两可( declare -p myarray
会立即显示问题)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.