如何在bash中连接跨行的字符串?

如何在bash中连接跨行的字符串?

在脚本.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 你的问题的解决方案实际上非常简单。您可以使用 function 方法,也可以使用单 lash 方法也适用于多行注释,而无需在每行上使用 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.

相关内容