我有这个输入文件
first line
second line
wow! something
the last line
我使用" line"填充数组。 word whit这个脚本
#!/bin/bash
IFS_backup=$IFS
IFS=$'\n'
lines=($(grep "line" "$1"))
IFS=IFS_backup
i=0
for line in "${lines[@]}"
do
echo $line
echo "$line"
done
我得到了这个输出
first line
first line
se ond line
second line
the l st line
the last line
这里发生了什么?我认为引号将绑定单词togheter,创建一个字符串。这里缺少的引号导致缺少随机字符...
谢谢!
注意:我知道还有其他方法用文件行填充数组。顺便说一句,这只是一个例子;我的实际数组以更棘手的方式填充,但引号行为是相同的。我想知道为什么这个剧本有了受限制的行为。
答案 0 :(得分:2)
您的IFS值有误。你需要
IFS="$IFS_backup"
而不是
IFS=IFS_backup
在您的情况下,字段分隔符包含字符IFS_backup
演示:
lines=($(seq 1020 1080))
IFS='246' # <-- the input field separator now any of the characters 2 or 4 or 6
for line in "${lines[@]}"
do
echo $line
done
打印
10 0
10 1
10
10 3
10
10 5
10
10 7
10 8
10 9
1030
1031
103
1033
103
1035
103
1037
1038
1039
10 0
10 1
10
10 3
10
10 5
10
10 7
10 8
10 9
1050
1051
105
1053
105
1055
105
1057
1058
1059
10 0
10 1
10
10 3
10
10 5
10
10 7
10 8
10 9
1070
1071
107
1073
107
1075
107
1077
1078
1079
1080
甚至更好的演示
#!/bin/bash
showargs() {
i=0
for arg in "$@"
do
let i++
echo "got arg $i:==$arg=="
done
i=0
for arg in "$*"
do
let i++
echo "print using the 1st char from IFS - got arg $i:==$arg=="
done
}
lines=(1233 12469 1469)
IFS='246'
for line in "${lines[@]}"
do
echo "============$line=============="
showargs $line
done
打印
============1233==============
got arg 1:==1==
got arg 2:==33==
print using the 1st char from IFS - got arg 1:==1233==
============12469==============
got arg 1:==1==
got arg 2:====
got arg 3:====
got arg 4:==9==
print using the 1st char from IFS - got arg 1:==12229==
============1469==============
got arg 1:==1==
got arg 2:====
got arg 3:==9==
print using the 1st char from IFS - got arg 1:==1229==