[英]How to read a columns from text file and store it in array? Bash
在文本文件中,每一行都包含一些单词。 看起来像
split time not big
every cash flu green big
numer note word
swing crash car out fly sweet
如何拆分这些行并将其存储在数组中? 我需要做这样的数组
for i in $file
do
echo "$array[0]"
echo "$array[2]"
done
有人可以帮忙吗?
您可以逐行读取文件中的行与read
和线路分配给数组。 它非常脆弱,可能会中断,具体取决于文件内容。
while read line; do
array=( $line )
echo "${array[0]}"
echo "${array[2]}"
done < file
解析文本文件的更好方法是使用awk
:
awk '{print $1; print $3}' file
我不明白为什么你需要一个数组。 您可以这样做:
while IFS= read -r line; do
read -r item1 item2 item3 <<< "$line"
printf '%s\n%s\n' "$item1" "$item3"
done < "$file"
但是,如果您愿意,也可以使read
给您一个数组:
read -ra array <<< "$line"
printf '%s\n%s\n' "${array[0]}" "${array[2]}"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.