Eu tenho uma operação usando cut
que gostaria de atribuir resultado a uma variável
var4=echo ztemp.xml |cut -f1 -d '.'
Eu recebo o erro:
ztemp.xml não é um comando
O valor de var4
nunca é atribuído; Estou tentando atribuir a saída de:
echo ztemp.xml | cut -f1 -d '.'
Como eu posso fazer isso?
Você deseja modificar sua tarefa para ler:
var4="$(echo ztemp.xml | cut -f1 -d '.')"
A construção $(…)
é conhecida como comando susbtitution .
Dependendo do Shell que você está usando, você pode usar a Expansão de Parâmetros. Por exemplo, em 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.
No seu caso, isso significaria fazer algo assim:
var4=ztemp.xml
var4=${var4%.*}
Observe que o caractere #
se comporta de maneira semelhante na parte do prefixo da string.
Ksh, Zsh e Bash oferecem outra sintaxe, talvez mais clara:
var4=$(echo ztemp.xml | cut -f1 -d '.')
Os backticks (também conhecidos como "sotaque grave") são ilegíveis em algumas fontes. A sintaxe $(blahblah)
é muito mais óbvia, pelo menos.
Observe que você pode canalizar valores em um comando read
em alguns shells:
ls -1 \*.\* | cut -f1 -d'.' | while read VAR4; do echo $VAR4; done
Essa é outra maneira de atribuir uma variável, boa para usar com alguns editores de texto que não conseguem destacar corretamente todos os códigos intricados que você cria.
read -r -d '' str < <(cat somefile.txt)
echo "${#str}"
echo "$str"