development

줄 바꿈이있는 유닉스 변수에 파일 내용

big-blog 2020. 8. 28. 07:53
반응형

줄 바꿈이있는 유닉스 변수에 파일 내용


다음 내용이 포함 된 텍스트 파일 test.txt가 있습니다.

text1
text2 

그리고 파일의 내용을 UNIX 변수에 할당하고 싶지만 이렇게하면 :

testvar=$(cat test.txt)
echo $testvar

결과는 다음과 같습니다.

text1 text2

대신에

text1
text2 

누군가 나에게 해결책을 제안 할 수 있습니까?


할당은 개행 문자를 제거 하지 않고 실제로 echo수행합니다. 줄 바꿈을 유지하려면 문자열을 따옴표로 묶어야합니다.

echo "$testvar"

이것은 당신이 원하는 결과를 줄 것입니다. 데모는 다음 내용을 참조하십시오.

pax> cat num1.txt ; x=$(cat num1.txt)
line 1
line 2

pax> echo $x ; echo '===' ; echo "$x"
line 1 line 2
===
line 1
line 2

이유 줄 바꿈은 공백으로 대체 이유가없는 완전히 와 함께 할 echo오히려 사물의 조합이다, 명령.

명령 줄이 주어지면 변수 bash에 대한 문서에 따라 단어로 분할합니다 IFS.

IFS : 확장 후 단어 분할에 사용되는 내부 필드 구분 기호입니다 <space><tab><newline>. 기본값은 .

기본적으로이 세 문자 중 하나를 사용하여 명령을 개별 단어로 분할 할 수 있습니다. 그 후에 단어 구분 기호가 사라지고 남은 것은 단어 목록뿐입니다.

이를 echo문서 ( bash내부 명령) 와 결합 하면 공백이 출력되는 이유를 알 수 있습니다.

echo [-neE] [arg ...] : 인자를 공백으로 구분하고 그 뒤에 줄 바꿈을 출력합니다.

를 사용 echo "$x"하면 전체 x변수가 에 따라 단일 단어가 bash되므로 분할되지 않습니다. 다음과 같이 확인할 수 있습니다.

pax> function count {
...>    echo $#
...> }
pax> count 1 2 3
3
pax> count a b c d
4
pax> count $x
4
pax> count "$x"
1

여기에서 count함수는 주어진 인수의 수를 간단히 출력합니다. 1 2 3a b c d변종 행동을 보여줍니다.

그런 다음 x변수 에 대한 두 가지 변형으로 시도합니다 . 없이 네 개의 단어가 있다는 것을 인용 쇼, "test", "1", "test""2". 따옴표를 추가하면 만들어 하나 하나 개의 단어 "test 1\ntest 2".


Bash -ge 4에는 표준 입력에서 배열 변수로 행을 읽는 맵 파일이 내장되어 있습니다.

help mapfile 

mapfile < file.txt lines
printf "%s" "${lines[@]}"

mapfile -t < file.txt lines    # strip trailing newlines
printf "%s\n" "${lines[@]}" 

또한보십시오:

http://bash-hackers.org/wiki/doku.php/commands/builtin/mapfile


This is due to IFS (Internal Field Separator) variable which contains newline.

$ cat xx1
1
2

$ A=`cat xx1`
$ echo $A
1 2

$ echo "|$IFS|"
|       
|

A workaround is to reset IFS to not contain the newline, temporarily:

$ IFSBAK=$IFS
$ IFS=" "
$ A=`cat xx1` # Can use $() as well
$ echo $A
1
2
$ IFS=$IFSBAK

To REVERT this horrible change for IFS:

IFS=$IFSBAK

Your variable is set correctly by testvar=$(cat test.txt). To display this variable which consist new line characters, simply add double quotes, e.g.

echo "$testvar" 

Here is the full example:

$ printf "test1\ntest2" > test.txt
$ testvar=$(<test.txt)
$ grep testvar <(set)
testvar=$'test1\ntest2'
$ echo "$testvar"
text1
text2
$ printf "%b" "$testvar"
text1
text2

Just if someone is interested in another option:

content=( $(cat test.txt) )

a=0
while [ $a -le ${#content[@]} ]
do
        echo ${content[$a]}
        a=$[a+1]
done

The envdir utility provides an easy way to do this. envdir uses files to represent environment variables, with file names mapping to env var names, and file contents mapping to env var values. If the file contents contain newlines, so will the env var.

See https://pypi.python.org/pypi/envdir

참고URL : https://stackoverflow.com/questions/2789319/file-content-into-unix-variable-with-newlines

반응형