Linux命令 mapfile - 從標(biāo)準(zhǔn)輸入讀取行并賦值到數(shù)組

2022-03-11 10:46 更新

mapfile

從標(biāo)準(zhǔn)輸入讀取行并賦值到數(shù)組。

概要

mapfile [-d delim] [-n count] [-O origin] [-s count] [-t] [-u fd] [-C callback] [-c quantum] [array]

主要用途

  • 從標(biāo)準(zhǔn)輸入或文件描述符讀取行并賦值到數(shù)組。

選項

-d delim       將delim設(shè)為行分隔符,代替默認的換行符。
-n count       從標(biāo)準(zhǔn)輸入中獲取最多count行,如果count為零那么獲取全部。
-O origin      從數(shù)組下標(biāo)為origin的位置開始賦值,默認的下標(biāo)為0。
-s count       跳過對前count行的讀取。
-t             讀取時移除行分隔符delim(默認為換行符)。
-u fd          從文件描述符fd中讀取。
-C callback    每當(dāng)讀取了quantum行時,調(diào)用callback語句。
-c quantum     設(shè)定讀取的行數(shù)為quantum。

如果使用-C時沒有同時使用-c指定quantum的值,那么quantum默認為5000。
當(dāng)callback語句執(zhí)行時,將數(shù)組下一個要賦值的下標(biāo)以及讀取的行作為額外的參數(shù)傳遞給callback語句。
如果使用-O時沒有提供起始位置,那么mapfile會在實際賦值之前清空該數(shù)組。

參數(shù)

array(可選):用于輸出的數(shù)組名稱。如果沒有指定數(shù)組名稱,那么會默認寫入到變量名為MAPFILE的數(shù)組中。

返回值

返回成功除非使用了非法選項、指定的數(shù)組是只讀的、指定的數(shù)組不是下標(biāo)數(shù)組。

例子

# 常見的讀取形式。
mapfile < source_file target_array
cat source_file |mapfile target_array
mapfile -u fd target_array

# 只讀取前5行。
mapfile < source_file -n 5 target_array

# 跳過前5行。
mapfile < source_file -s 5 target_array

# 在數(shù)組指定的下標(biāo)開始賦值。
# 請注意:這樣做不會清空該數(shù)組。
mapfile < source_file -O 2 target_array

# 讀取時設(shè)定行分隔符為tab。
# 注意,第二行的tab在終端需要用ctrl+v tab輸入;
mapfile < source_file -d $'\t' target_array
mapfile < source_file -d '	' target_array

# 讀取時移除行分隔符(tab)。
mapfile < source_file -d $'\t' -t target_array
# 讀取時移除行分隔符(換行符)。
mapfile < source_file -t target_array

# 每讀取2行,執(zhí)行一次語句(在這里是echo)。
mapfile < source_file -C "echo CALLBACK:" -c 2 target_array

# 遍歷下標(biāo),依次顯示數(shù)組的元素。
for i in ${!target_array[@]}; do
  printf "%s" ${target_array[i]}
done

注意

  1. 該命令是bash內(nèi)建命令,相關(guān)的幫助信息請查看help命令。
  2. bash內(nèi)建命令readarray是mapfile的同義詞。


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號