繁体   English   中英

将文件读入 bash 阵列

[英]Read file into bash array

我怎样才能使这项工作?

我有测试数据:test.dat

red apples
green tomato
yellow lemon

我已经尝试了许多示例,但都无济于事。

显然shell有些东西我不明白......

#!/bin/bash

#lines=$(IFS='\n' cat $1)
#IFS=$'\r\n' GLOBIGNORE='*' command eval  
#lines=($(cat test.dat))
#IFS=$'\n' read -d '' -r -a lines < test.dat
#readarray -t lines < test.dat
#lines=$(cat test.dat)

lines=$(< test.dat)


for line in $lines
do
  echo "${line}"
done

printf "line 1: %s\n" "${lines[1]}"
echo "line 2: ${lines[2]}"

Output:

./test.sh test.dat
red
apples
green
tomato
yellow
lemon
./test.sh line 71: lines[1]: unbound variable

使用 readarray 命令应该可以工作, readarray -ta < /path/to/filename

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM