
작업이 있는데 cut
결과를 변수에 할당하고 싶습니다.
var4=echo ztemp.xml |cut -f1 -d '.'
오류가 발생합니다.
ztemp.xml은 명령이 아닙니다
값은 var4
할당되지 않습니다. 출력에 할당하려고 합니다.
echo ztemp.xml | cut -f1 -d '.'
어떻게 해야 하나요?
답변1
답변2
사용하는 셸에 따라 매개변수 확장을 사용할 수 있습니다. 예를 들면 다음과 같습니다 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.
귀하의 경우 이는 다음과 같은 작업을 수행하는 것을 의미합니다.
var4=ztemp.xml
var4=${var4%.*}
문자는 #
문자열의 접두사 부분에서도 유사하게 동작합니다.
답변3
Ksh, Zsh 및 Bash는 모두 더 깔끔한 대체 구문을 제공합니다.
var4=$(echo ztemp.xml | cut -f1 -d '.')
일부 글꼴에서는 백틱("악센트"라고도 함)을 읽을 수 없습니다. 구문은 $(blahblah)
적어도 더 분명합니다.
read
일부 셸에서는 값을 명령으로 파이프 할 수 있습니다 .
ls -1 \*.\* | cut -f1 -d'.' | while read VAR4; do echo $VAR4; done
답변4
이는 변수를 할당하는 또 다른 방법이며, 생성한 모든 복잡한 코드를 적절하게 강조 표시하지 않는 일부 텍스트 편집기와 함께 사용하기에 좋습니다.
read -r -d '' str < <(cat somefile.txt)
echo "${#str}"
echo "$str"