我试图将包含行文件读入Bash数组。

到目前为止,我尝试了以下几种方法:

Attempt1

a=( $( cat /path/to/filename ) )

Attempt2

index=0
while read line ; do
    MYARRAY[$index]="$line"
    index=$(($index+1))
done < /path/to/filename

这两种尝试都只返回一个包含文件第一行的元素数组。我做错了什么?

我运行bash 4.1.5


当前回答

一种替代方法,如果文件包含字符串没有空格,每行1string:

fileItemString=$(cat  filename |tr "\n" " ")

fileItemArray=($fileItemString)

检查:

打印整个数组:

${fileItemArray[*]}

Length=${#fileItemArray[@]}

其他回答

#!/bin/bash
IFS=$'\n' read  -d '' -r -a inlines  < testinput
IFS=$'\n' read  -d '' -r -a  outlines < testoutput
counter=0
cat testinput | while read line; 
do
    echo "$((${inlines[$counter]}-${outlines[$counter]}))"
    counter=$(($counter+1))
done
# OR Do like this
counter=0
readarray a < testinput
readarray b < testoutput
cat testinput | while read myline; 
do
    echo value is: $((${a[$counter]}-${b[$counter]}))
    counter=$(($counter+1))
done

你的第一次尝试很接近。下面是使用你的想法的简单方法。

file="somefileondisk"
lines=`cat $file`
for line in $lines; do
        echo "$line"
done

一种替代方法,如果文件包含字符串没有空格,每行1string:

fileItemString=$(cat  filename |tr "\n" " ")

fileItemArray=($fileItemString)

检查:

打印整个数组:

${fileItemArray[*]}

Length=${#fileItemArray[@]}

readarray命令(也可以拼写为mapfile)是在bash 4.0中引入的。

readarray -t a < /path/to/filename

将文件的每一行读入bash数组的最简单方法是:

IFS=$'\n' read -d '' -r -a lines < /etc/passwd

现在只需索引到数组行来检索每一行,例如。

printf "line 1: %s\n" "${lines[0]}"
printf "line 5: %s\n" "${lines[4]}"

# all lines
echo "${lines[@]}"