在bash中,是否可以从文本文件加载新行到变量中?
文本文件是什么样的?
EXAMPLEfoo
EXAMPLEbar
EXAMPLE1
EXAMPLE2
EXAMPLE3
EXAMPLE4
变量会变成什么?
$1 = EXAMPLEfoo
$2 = EXAMPLEbar
等等,还有其他的吗?
在bash中,是否可以从文本文件加载新行到变量中?
文本文件是什么样的?
EXAMPLEfoo
EXAMPLEbar
EXAMPLE1
EXAMPLE2
EXAMPLE3
EXAMPLE4
变量会变成什么?
$1 = EXAMPLEfoo
$2 = EXAMPLEbar
等等,还有其他的吗?
$ s=$(<file)
$ set -- $s
$ echo $1
EXAMPLEfoo
$ echo $2
EXAMPLEbar
$ echo $@
EXAMPLEfoo EXAMPLEbar EXAMPLE1 EXAMPLE2 EXAMPLE3 EXAMPLE4
我会通过消除临时变量s来改进上面的代码:$ set -- $(<file)
如果您的输入文件长这样
variable1 = value
variable2 = value
你可以使用以下结构来获取命名变量。input=`cat filename|grep -v "^#"|grep "\c"`
set -- $input
while [ $1 ]
do
eval $1=$3
shift 3
done
cat somefile.txt| xargs bash_command.sh
bash_command.sh将接收这些行作为参数
saveIFS="$IFS"
IFS=$'\n'
array=($(<file))
IFS="$saveIFS"
echo ${array[0]} # output: EXAMPLEfoo
echo ${array[1]} # output: EXAMPLEbar
for i in "${array[@]}"; do echo "$i"; done # iterate over the array
编辑:
你的pastebin中的循环存在一些问题。以下是你发布的代码:
for i in "${array[@]}"; do echo " "AD"$count = "$i""; $((count=count+1)); done
这是正确的格式:
for i in "${array[@]}"; do declare AD$count="$i"; ((count=count+1)); done
或者
for i in "${array[@]}"; do declare AD$count="$i"; ((count++)); done
但为什么不直接使用数组呢?您可以将其称为AD,而不是数组,并且不需要访问名为“AD4”的变量,而是访问数组元素“${AD[4]}”。
echo "${AD[4]}"
if [[ ${AD[9]} == "EXAMPLE value" ]]; then do_something; fi
如果您不需要将这些变量作为脚本的输入,则可以使用数组来完成此操作。从高级脚本指南中提取的push()
函数。
push() # Push item on stack.
{
if [ -z "$1" ] # Nothing to push?
then
return
fi
let "SP += 1" # Bump stack pointer.
stack[$SP]=$1
return
}
/tmp/test
的内容
[root@x~]# cat /tmp/test
EXAMPLEfoo
EXAMPLEbar
EXAMPLE1
EXAMPLE2
EXAMPLE3
EXAMPLE4
SP=0; for i in `cat /tmp/test`; do push $i ; done
那么
[root@x~]# echo ${stack[3]}
EXAMPLE1
eval "$(VBoxManage showvminfo "$VMname" --details --machinereadable | egrep "^(name|UUID|CfgFile|VMState)")"
echo "$name {$UUID} $VMState ($VMStateChangeTime) CfgFile=$CfgFile"
附言: 如果您的名称被引用或包含破折号,则任何内容都不起作用。 如果您有像 VBoxManage 输出中那样的东西(“IDE-1-0”=“emptydrive”等),可以像我的示例一样使用egrep仅搜索特定值,或者将错误静音。
然而,沉默错误总是很危险的。您永远不知道下一个值是否会有未引用的“*”,因此必须非常小心地处理以这种方式加载的值,并采取所有必要的预防措施。