Bash에서 여러 줄에 걸쳐 문자열을 연결하는 방법은 무엇입니까?

Bash에서 여러 줄에 걸쳐 문자열을 연결하는 방법은 무엇입니까?

script.sh에서:

#!/bin/bash
# Above is a while statement, so the printf has a indent(actually are 3 spaces)
   printf "I am a too long sentence in line1, I need to switch to a new line. \n\
   I'd like to be at the head of this line2, but actually there are 3 redundant spaces \n"

코드에서 말했듯이 다음과 같이 표시됩니다.

I am a too long sentence in line1, I need to switch to a new line.
      I'd like to be at the head of this line2, but actually there are 3 redundant spaces

printf이 문제를 해결하려면 모든 행에 a를 사용해야 합니다 . 좋다:

   printf "I am a too long sentence in line1, I need to switch to a new line. \n"
   printf "I'd like to be at the head of this line2, but actually there are 3 redundant spaces \n"

너무 멍청한 것 같은데 왜 아래와 같이 문자열을 연결합니까?

   printf {"a\n"
   "b"}

   # result should be like below
a
b

답변1

printf일반적인 방법을 사용할 수 있습니다 . 첫 번째 문자열은 형식을 정의하고 다음 문자열은 매개변수입니다.

예:

#!/bin/bash
   printf '%s\n' "I am a too long sentence in line1, I need to switch to a new line."\
      "I'd like to be at the head of this line2, but actually there are 3 redundant spaces."\
            "I don't care how much indentation is used"\
 "on the next line."

산출:

I am a too long sentence in line1, I need to switch to a new line.
I'd like to be at the head of this line2, but actually there are 3 redundant spaces.
I don't care how much indentation is used
on the next line.

답변2

@Freddy의 방법은 prinf를 기반으로 합니다. 들여쓰기 없이 여러 줄로 문자열을 작성하는 일반적인 방법을 찾았습니다.

#!/bin/bash
concat() {
  local tmp_arg
  for each_arg in $@
  do
    tmp_arg=${tmp_arg}${each_arg}
  done
  echo ${tmp_arg}
}

# indent free
   str=$(concat "hello1\n" \
   "hello2\n" \
   hello3)
   printf $str"\n"

결과:

hello1
hello2
hello3

답변3

@Anon 문제에 대한 해결책은 실제로 매우 간단합니다. 함수 방법을 사용할 수 있으며 각 줄에 printf를 사용하지 않고도 여러 줄 주석에도 단일 속눈썹 방법이 작동합니다.

해결책:

echo "This is the first line. " \
> "This is second line"

산출:

This is first line. This is second line

이 방법을 사용하여 단일 echo 명령으로 여러 문자열을 연결할 수 있습니다. 슬래시를 사용하면 새 문장을 추가할 수 있는 두 번째 빈 줄이 생깁니다.

답변4

따옴표 안에 줄 바꿈을 추가할 수 있습니다. 즉, 따옴표가 같은 줄로 끝날 필요가 없으므로 연속된 문자가 없어도 여러 줄 문자열을 가질 수 있습니다. 이 시도:

#! /bin/bash

echo "This text has
several lines.
This is another
sentence."

         echo "This line is printed starting from the left margin
    and these lines
    are indented
    by four spaces"

printf "This text contains
not %d, but %d two substitution
fields.\n" 1 2

이는

This text has
several lines.
This is another
sentence.
This line is printed starting from the left margin
    and these lines
    are indented
    by four spaces
This text contains
not 1, but 2 two substitution
fields.

관련 정보