从文本文件中读取不同的行并在 bash shell 中设置不同的变量 [英] Read different lines from a text file and set different variables in bash shell
问题描述
我有一个包含不同行的文本文件,例如:
VMNAME-1="blah1"VMANME-2="blah2"VMIP-1=12.34.56.78VMIP-2=98.76.54.32通过=某事"用户=其他"
我想读取这个文本文件并在 bash shell 中使用这些值,如下所示:
create_vm.exp VMIP-1 用户密码 VMNAME-1create_vm.exp VMIP-2 用户密码 VMNAME-2
关于如何做到这一点的任何建议?
如果等号左边的符号名称没有包含 -
,那么你可以简单地 source
脚本,因为所有行都是有效的 Bash 表达式.
然而,这里的情况并非如此,因为 VMNAME-1
和其他人确实包含一个 -
,所以 VMNAME-1
是在 Bash 中不是有效的变量名.
如果您确定等号后面的值都不包含 -
,那么您可以简单地将所有出现的 -
替换为 _
使这些行成为有效的 Bash 表达式,如下所示:
然后你可以像这样编写创建 VM 命令:
create_vm.exp "$VMIP_1" "$USER" "$PASS" "$VMNAME_1"create_vm.exp "$VMIP_2" "$USER" "$PASS" "$VMNAME_2"
如果值可能包含-
,那么您需要更努力地将-
替换为仅在等号左侧的位置.这是一个可能的简单解决方法,在某些情况下可行,但可能不是全部:
这仅替换以 V
开头的行上的 -
,并且仅替换第一次出现的行.
I have a text file with different lines like:
VMNAME-1="blah1"
VMANME-2="blah2"
VMIP-1=12.34.56.78
VMIP-2=98.76.54.32
PASS="something"
USER="else"
and I want to read this text file and use these values in a bash shell in lines like this:
create_vm.exp VMIP-1 USER PASS VMNAME-1
create_vm.exp VMIP-2 USER PASS VMNAME-2
any suggestion about how to do that?
If the symbol names on the left side of the equal signs hadn't contained a -
, then you could simply source
the script, as all the lines would be valid Bash expressions.
However, that is not the case here, as VMNAME-1
and others do contain a -
, and so VMNAME-1
is not a valid variable name in Bash.
If you know for certain that none of the values after the equal sign will contain -
, then you could simply replace all occurrences of -
with _
to make the lines valid Bash expressions like this:
. <(tr -- - _ < input.txt)
And then you could write the create VM commands like this:
create_vm.exp "$VMIP_1" "$USER" "$PASS" "$VMNAME_1"
create_vm.exp "$VMIP_2" "$USER" "$PASS" "$VMNAME_2"
If the values may contain -
, then you need to work a bit harder to replace -
only at the left side of the equal sign. Here's a possible simple workaround that would work in some cases, but maybe not all:
. <(sed -e '/^V/s/-/_/' < input.txt)
This replaces -
only on lines that start with V
, and only the first occurrences.
这篇关于从文本文件中读取不同的行并在 bash shell 中设置不同的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!