Programing

여분의 공간이있는 여러 줄 문자열 (보존 들여 쓰기)

lottogame 2020. 3. 3. 22:53
반응형

여분의 공간이있는 여러 줄 문자열 (보존 들여 쓰기)


다음과 같이 미리 정의 된 텍스트를 파일에 쓰고 싶습니다.

text="this is line one\n
this is line two\n
this is line three"

echo -e $text > filename

나는 이와 같은 것을 기대하고있다 :

this is line one
this is line two
this is line three

그러나 이것을 얻었다 :

this is line one
 this is line two
 this is line three

나는 각각 뒤에 공간이 없다고 \n생각하지만 여분의 공간은 어떻게 나옵니까?


Heredoc이이 목적에 더 편리하게 들립니다. ex 또는 cat 과 같은 명령 인터프리터 프로그램에 여러 명령을 보내는 데 사용됩니다.

cat << EndOfMessage
This is line 1.
This is line 2.
Line 3.
EndOfMessage

이후의 문자열 <<은 중지 할 위치를 나타냅니다.

이 줄을 파일로 보내려면 다음을 사용하십시오.

cat > $FILE <<- EOM
Line 1.
Line 2.
EOM

다음 줄을 변수에 저장할 수도 있습니다.

read -r -d '' VAR << EOM
This is line 1.
This is line 2.
Line 3.
EOM

이것은라는 변수에 행을 저장합니다 VAR.

인쇄 할 때 변수 주위의 따옴표를 기억하십시오. 그렇지 않으면 줄 바꿈 문자가 표시되지 않습니다.

echo "$VAR"

또한 들여 쓰기를 사용하여 코드에서 더 두드러지게 만들 수 있습니다. 이번에 는 탭이 나타나지 않도록 -애프터 <<추가하십시오 .

read -r -d '' VAR <<- EOM
    This is line 1.
    This is line 2.
    Line 3.
EOM

그러나 코드에서 들여 쓰기를 위해 공백이 아닌 탭을 사용해야합니다.


문자열을 변수로 가져 오려고하면 쉬운 또 다른 방법은 다음과 같습니다.

USAGE=$(cat <<-END
    This is line one.
    This is line two.
    This is line three.
END
)

탭으로 문자열을 들여 쓰면 (예 : '\ t') 들여 쓰기가 제거됩니다. 공백으로 들여 쓰기하면 들여 쓰기가 그대로 유지됩니다.

참고 : 마지막 닫는 괄호가 다른 줄에 있음을 의미. END텍스트는 그 자체로 한 줄에 표시되어야합니다.


echo전달 된 인수 사이에 공백을 추가합니다. $text변수 확장 및 단어 분할이 적용되므로 echo명령은 다음과 같습니다.

echo -e "this" "is" "line" "one\n" "this" "is" "line" "two\n"  ...

"this"앞에 공백이 추가 될 것입니다. 개행 문자를 제거하고 개행 $text을 유지하기 위해 인용 할 수 있습니다 .

text="this is line one
this is line two
this is line three"

echo "$text" > filename

또는 다음 printf보다 더 강력하고 휴대하기 쉬운를 사용할 수 있습니다 echo.

printf "%s\n" "this is line one" "this is line two" "this is line three" > filename

에서 bash중괄호 확장을 지원하는, 당신도 할 수 :

printf "%s\n" "this is line "{one,two,three} > filename

bash 스크립트에서 다음이 작동합니다.

#!/bin/sh

text="this is line one\nthis is line two\nthis is line three"
echo $text > filename

대안 적으로 :

text="this is line one
this is line two
this is line three"
echo "$text" > filename

고양이 파일 이름은 다음을 제공합니다.

this is line one
this is line two
this is line three

모든 줄을 올바르게 들여 쓰기를 원했기 때문에 더 많은 솔루션을 찾았습니다.

  1. 당신은 사용할 수 있습니다 echo:

    echo    "this is line one"   \
        "\n""this is line two"   \
        "\n""this is line three" \
        > filename
    

    줄 끝에 "\n"바로 넣으면 작동하지 않습니다 \.

  2. 또는 printf더 나은 이식성을 위해 사용할 수 있습니다 (와 관련하여 많은 문제가 발생했습니다 echo).

    printf '%s\n' \
        "this is line one"   \
        "this is line two"   \
        "this is line three" \
        > filename
    
  3. 또 다른 해결책은 다음과 같습니다.

    text=''
    text="${text}this is line one\n"
    text="${text}this is line two\n"
    text="${text}this is line three\n"
    printf "%b" "$text" > filename
    

    또는

    text=''
    text+="this is line one\n"
    text+="this is line two\n"
    text+="this is line three\n"
    printf "%b" "$text" > filename
    
  4. 다른 용액을 혼합하여 달성 printf하고 sed.

    if something
    then
        printf '%s' '
        this is line one
        this is line two
        this is line three
        ' | sed '1d;$d;s/^    //g'
    fi
    

    들여 쓰기 수준을 코드에 하드 코딩 할 때 이와 같은 형식의 코드를 리팩터링하는 것은 쉽지 않습니다.

  5. 도우미 함수와 일부 변수 대체 트릭을 사용할 수 있습니다.

    unset text
    _() { text="${text}${text+
    }${*}"; }
    # That's an empty line which demonstrates the reasoning behind 
    # the usage of "+" instead of ":+" in the variable substitution 
    # above.
    _ ""
    _ "this is line one"
    _ "this is line two"
    _ "this is line three"
    unset -f _
    printf '%s' "$text"
    

다음은 여러 줄 문자열을 변수에 할당하는 선호되는 방법입니다 (멋지다고 생각합니다).

read -r -d '' my_variable << \
_______________________________________________________________________________

String1
String2
String3
...
StringN
_______________________________________________________________________________

밑줄의 수는 두 경우 모두 동일합니다 (여기서는 80).


아래와 같이 넣으면 작동합니다.

AA='first line
\nsecond line 
\nthird line'
echo $AA
output:
first line
second line
third line

참고 URL : https://stackoverflow.com/questions/23929235/multi-line-string-with-extra-space-preserved-indentation



반응형