[英]How do I make a command a variable
A relative newbie here. 这里是一个相对新手。 I'm reading in a file using the following commands:
我正在使用以下命令读取文件:
while read line
do
commands here
done < file
I'm splitting the line into two parts separated by a dash by the following 我将线分为两部分,以下用破折号分隔
dash_pos=`expr index "$line" -`
dash_pos
is obviously not a constant that's why I make it a variable. dash_pos
显然不是常量,这就是为什么我将其dash_pos
变量。
I can now do the following 我现在可以执行以下操作
Part1=${line:0:$dash_pos -2}
Part2=${line:$dash_pos + 1}
These commands work as expected. 这些命令按预期方式工作。
Is there a way that I can make the string manipulation commands a variable eg 有没有一种方法可以使字符串操作命令成为变量,例如
Find_Part1=${line:0:$dash_pos -2}
Find_Part2=${line:$dash_pos + 1}
so that 以便
Part1=$Find_Part1 & Part2=$Find_Part2
work as before, but it will then allow me to do 像以前一样工作,但是它将允许我做
Part1=$Find_Part2 & Part2=$Find_Part1
when necessary. 必要时。
Any help will be appreciated as I have tried quotes, double quotes, brackets, curly brackets and back ticks in a variety of combinations to try and get this to work. 任何帮助将不胜感激,因为我尝试了各种组合的引号,双引号,方括号,大括号和反勾号,以尝试使此方法起作用。 John
约翰
Storing executable code in a variable is far more trouble than it is worth. 将可执行代码存储在变量中的麻烦远不止于此。 Use functions instead:
使用函数代替:
Find_Part1 () {
printf "%s" "${line:0:$dash_pos -2}"
}
Find_Part2 () {
printf "%s" "${line:$dash_pos + 1}"
}
Part1=$(Find_Part1)
Part2=$(Find_Part2)
It appears, though, that what you really want is something along the lines of 但是,您似乎真正想要的是
while IFS="-" read Part1 Part2; do
...
done < file
to let the read
command split line
into Part1
and Part2
for you. 让
read
命令为您将line
分为Part1
和Part2
。
It is unclear why you cannot just do what is literally in the question: 目前尚不清楚为什么您不能仅仅执行问题中的字面意思:
# get the parts
Find_Part1=${line:0:$dash_pos -2}
Find_Part2=${line:$dash_pos + 1}
# ... as necessary:
if such and such condition ; then
Part1=$Find_Part1
Part2-$Find_Part2
else
Part1=$Find_Part2
Part2=$Find_Part1
fi
Also, you can instead exchange the values of Part1
and Part2
when necessary, requiring only one temporary variable 另外,您可以根据需要交换
Part1
和Part2
的值,只需要一个临时变量
if interesting condition ; then
temp=$Part1; Part1=$Part2; Part2=$temp
fi
Inside a Bash function, we would might make temp
a local to avoid name clashes and namespace clutter: 在Bash函数内部,我们可能将
temp
为local,以避免名称冲突和名称空间混乱:
local temp
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.