![명령 출력을 변수에 할당할 때 새 줄이 공백으로 대체됩니다. [중복]](https://linux55.com/image/197351/%EB%AA%85%EB%A0%B9%20%EC%B6%9C%EB%A0%A5%EC%9D%84%20%EB%B3%80%EC%88%98%EC%97%90%20%ED%95%A0%EB%8B%B9%ED%95%A0%20%EB%95%8C%20%EC%83%88%20%EC%A4%84%EC%9D%B4%20%EA%B3%B5%EB%B0%B1%EC%9C%BC%EB%A1%9C%20%EB%8C%80%EC%B2%B4%EB%90%A9%EB%8B%88%EB%8B%A4.%20%5B%EC%A4%91%EB%B3%B5%5D.png)
파일이 있는데 패턴별로 콘텐츠를 파악하고("패턴 생성") 해당 콘텐츠를 bash 변수에 저장하여 컬 문에서 사용할 수 있도록 하는 아이디어입니다. 내 명령은 작동하지만 문제는 출력이 변수에 할당될 때 새 줄이 공백으로 대체된다는 것입니다.
파일 예
...
example1
example2
create mode 100644 repo/linux-image-5.4.0-89-generic_5.4.0-89.100_amd64.deb
create mode 100644 repo/linux-modules-5.4.0-89-generic_5.4.0-89.100_amd64.deb
create mode 100644 repo/python3.8-minimal_3.8.10-0ubuntu1~20.04.1_amd64.deb
create mode 100644 repo/python3.8_3.8.10-0ubuntu1~20.04.1_amd64.deb
example3
example4
...
그랩해야 해오직우분투는 이를 패키지화하여 bash 변수에 저장합니다 var
. 아이디어는 형식을 유지하는 것입니다( 사용 \n
).
grep, sed 및 printf를 사용하여 출력을 수정하고 출력을 변수에 할당해 보았습니다.
사용예grep and printf
test_variable=$( cat file.txt | grep "create mode" )
var=$( printf '%s\n' "${test_variable//' create mode 100644 repo/'/}" )
echo $var
repo/linux-image-5.4.0-89-generic_5.4.0-89.100_amd64.deb repo/linux-modules-5.4.0-89-generic_5.4.0-89.100_amd64.deb repo/python3.8-minimal_3.8.10-0ubuntu1~20.04.1_amd64.deb repo/python3.8_3.8.10-0ubuntu1~20.04.1_amd64.deb
동일한 printf 명령을 사용하지만 출력을 변수에 할당하지 않은 경우 결과는 다음과 같습니다.
linux-image-5.4.0-89-generic_5.4.0-89.100_amd64.deb
linux-modules-5.4.0-89-generic_5.4.0-89.100_amd64.deb
python3.8-minimal_3.8.10-0ubuntu1~20.04.1_amd64.deb
python3.8_3.8.10-0ubuntu1~20.04.1_amd64.deb
tr
이 문제를 해결하기 위해 다른 방법을 사용해 보았습니다 .
다른 예제 사용sed
sed -e '/create mode/!d' file.txt
create mode 100644 repo/linux-image-5.4.0-89-generic_5.4.0-89.100_amd64.deb
create mode 100644 repo/linux-modules-5.4.0-89-generic_5.4.0-89.100_amd64.deb
create mode 100644 repo/python3.8-minimal_3.8.10-0ubuntu1~20.04.1_amd64.deb
create mode 100644 repo/python3.8_3.8.10-0ubuntu1~20.04.1_amd64.deb
그건 문제가 되지 않습니다. 하지만 이 출력을 변수에 할당하려고 하면 개행 문자가 공백으로 대체됩니다.
var=$( sed -e '/create mode/!d' file.txt )
echo $var
create mode 100644 repo/linux-image-5.4.0-89-generic_5.4.0-89.100_amd64.deb create mode 100644 repo/linux-modules-5.4.0-89-generic_5.4.0-89.100_amd64.deb create mode 100644 repo/python3.8-minimal_3.8.10-0ubuntu1~20.04.1_amd64.deb create mode 100644 repo/python3.8_3.8.10-0ubuntu1~20.04.1_amd64.deb
이 문제를 해결하는 데 도움을 주실 수 있나요? 감사해요
답변1
다음을 사용하면 잘 작동합니다 echo "$var"
.
$ valor=$( cat <<EOF
> hola
> adios
> EOF
> )
$ echo $valor
hola adios
$ echo "$valor"
hola
adios
$