Vas*_*ass 30 command-line scripting bash shell-script coreutils
我有一个操作cut,我想将结果分配给一个变量
var4=echo ztemp.xml |cut -f1 -d '.'
Run Code Online (Sandbox Code Playgroud)
我收到错误:
ztemp.xml 不是命令
var4never的值被赋值;我正在尝试为其分配以下输出:
echo ztemp.xml | cut -f1 -d '.'
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?
Tok*_*Tok 43
您需要修改您的作业以阅读:
var4="$(echo ztemp.xml | cut -f1 -d '.')"
Run Code Online (Sandbox Code Playgroud)
该$(…)构造称为命令 susbtitution。
根据您使用的外壳,您可以使用参数扩展。例如在bash:
${parameter%word}
${parameter%%word}
Remove matching suffix pattern. The word is expanded to produce
a pattern just as in pathname expansion. If the pattern matches
a trailing portion of the expanded value of parameter, then the
result of the expansion is the expanded value of parameter with
the shortest matching pattern (the ``%'' case) or the longest
matching pattern (the ``%%'' case) deleted. If parameter is @
or *, the pattern removal operation is applied to each posi?
tional parameter in turn, and the expansion is the resultant
list. If parameter is an array variable subscripted with @ or
*, the pattern removal operation is applied to each member of
the array in turn, and the expansion is the resultant list.
Run Code Online (Sandbox Code Playgroud)
在你的情况下,这意味着做这样的事情:
var4=ztemp.xml
var4=${var4%.*}
Run Code Online (Sandbox Code Playgroud)
请注意,字符#在字符串的前缀部分的行为方式类似。
Ksh、Zsh 和 Bash 都提供了另一种可能更清晰的语法:
var4=$(echo ztemp.xml | cut -f1 -d '.')
Run Code Online (Sandbox Code Playgroud)
反引号(又名“重音符”)在某些字体中不可读。该$(blahblah)语法是很多更加明显,至少。
请注意,您可以将值通过管道传输到read某些 shell 中的命令中:
ls -1 \*.\* | cut -f1 -d'.' | while read VAR4; do echo $VAR4; done
Run Code Online (Sandbox Code Playgroud)