#Bash 的 mapfile 命令
mapfile [OPTION]... [ARRAY]
功能
按行读取输入并写入数组中。
此命令和
readarray完全相同。
类型
Bash 内置命令。
参数
OPTION选项:-d delim- 使用delim作为行的分隔符;默认为换行符(\n)-n count- 最多读取count行;如果count是 0 则读取全部行-O origin- 从数组ARRAY的第origin个元素开始赋值;默认从 0 开始-s count- 丢弃开头的count行-t- 丢弃行末的分隔符-u fd- 从文件描述符fd读取;默认为标准输入-C callback- 每读取quantum行调用一次callback-c quantum- 每读取quantum行调用一次callback
ARRAY- 要写入的数组变量名;省略此参数则默认写入变量MAPFILE
#示例
基础使用
$ mapfile arr < <(echo -e "1\n2\n3") # 将 "1\n2\n3" 读入数组 arr
$ echo -e "${arr[0]}" # 内容包含末尾的换行符
1
$ echo -e "${arr[1]}"
2
$ echo -e "${arr[2]}"
3
注意,不能使用
echo -e "1\n2\n3" | mapfile arr,因为管道|运行在子 shell 中,使得外层 shell 没有arr变量。
去除分隔符
$ mapfile -t arr < <(echo -e "1\n2\n3") # 将 "1\n2\n3" 读入数组 arr
$ echo -e "${arr[0]}" # 换行符被移除
1
$ echo -e "${arr[1]}"
2
$ echo -e "${arr[2]}"
3
指定索引
$ mapfile -t -s 2 -O 3 arr < <(echo -e "a\nb\nc\nd") # 丢弃前 2 行,之后读取的内容写入 arr[3] 及之后的元素
$ echo -e "${arr[@]}"
1 2 3 c d
#相关命令
mapfile和readarray是完全相同的命令。
#手册
mapfile: mapfile [-d delim] [-n count] [-O origin] [-s count] [-t] [-u fd] [-C callback] [-c quantum] [array]
Read lines from the standard input into an indexed array variable.
Read lines from the standard input into the indexed array variable ARRAY, or
from file descriptor FD if the -u option is supplied. The variable MAPFILE
is the default ARRAY.
Options:
-d delim Use DELIM to terminate lines, instead of newline
-n count Copy at most COUNT lines. If COUNT is 0, all lines are copied
-O origin Begin assigning to ARRAY at index ORIGIN. The default index is 0
-s count Discard the first COUNT lines read
-t Remove a trailing DELIM from each line read (default newline)
-u fd Read lines from file descriptor FD instead of the standard input
-C callback Evaluate CALLBACK each time QUANTUM lines are read
-c quantum Specify the number of lines read between each call to
CALLBACK
Arguments:
ARRAY Array variable name to use for file data
If -C is supplied without -c, the default quantum is 5000. When
CALLBACK is evaluated, it is supplied the index of the next array
element to be assigned and the line to be assigned to that element
as additional arguments.
If not supplied with an explicit origin, mapfile will clear ARRAY before
assigning to it.
Exit Status:
Returns success unless an invalid option is given or ARRAY is readonly or
not an indexed array.