使用Bash将文件内容提取到数组中

时间:2021-06-07 06:43:11

How to extract a file content into array in Bash line by line. Each line is set to an element.

如何逐行在Bash中将文件内容提取到数组中。每一行都设置为一个元素。

I've tried this:

我试过这个:

declare -a array=(`cat "file name"`)

but it didn't work, it extracts the whole lines into [0] index element

但它不起作用,它将整行提取到[0]索引元素中

3 个解决方案

#1


23  

You can use a loop to read each line of your file and put it into the array

您可以使用循环读取文件的每一行并将其放入数组中

# Read the file in parameter and fill the array named "array"
getArray() {
    array=() # Create array
    while IFS= read -r line # Read a line
    do
        array+=("$line") # Append line to the array
    done < "$1"
}

getArray "file.txt"

How to use your array :

如何使用你的数组:

# Print the file (print each element of the array)
getArray "file.txt"
for e in "${array[@]}"
do
    echo "$e"
done

#2


28  

For bash version 4, you can use:

对于bash版本4,您可以使用:

readarray -t array < file.txt

#3


2  

This might work for you (Bash):

这可能适合你(Bash):

OIFS="$IFS"; IFS=$'\n'; array=($(<file)); IFS="$OIFS"

Copy $IFS, set $IFS to newline, slurp file into array and reset $IFS back again.

复制$ IFS,将$ IFS设置为换行符,将文件设置为数组并再次重置$ IFS。

#1


23  

You can use a loop to read each line of your file and put it into the array

您可以使用循环读取文件的每一行并将其放入数组中

# Read the file in parameter and fill the array named "array"
getArray() {
    array=() # Create array
    while IFS= read -r line # Read a line
    do
        array+=("$line") # Append line to the array
    done < "$1"
}

getArray "file.txt"

How to use your array :

如何使用你的数组:

# Print the file (print each element of the array)
getArray "file.txt"
for e in "${array[@]}"
do
    echo "$e"
done

#2


28  

For bash version 4, you can use:

对于bash版本4,您可以使用:

readarray -t array < file.txt

#3


2  

This might work for you (Bash):

这可能适合你(Bash):

OIFS="$IFS"; IFS=$'\n'; array=($(<file)); IFS="$OIFS"

Copy $IFS, set $IFS to newline, slurp file into array and reset $IFS back again.

复制$ IFS,将$ IFS设置为换行符,将文件设置为数组并再次重置$ IFS。