相当于bash中python的textwarp dedent

2024-09-30 01:28:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我在bash中有一个包含多行字符串的变量:

mystring="foo
          bar
          stack
          overflow"

显然,当I echo "$mystring"时,这会产生大量的缩进。在python中,我只需导入textwarp并在字符串上使用dedent,这就把我带到了这里。有没有类似python的dedent模块为bash而存在?在


Tags: 模块字符串echobashfoostackbarmystring
3条回答

可以使用sed从每行删除前导空格:

$ sed 's/^[[:space:]]*//' <<< "$mystring"
foo
bar
stack
overflow

您可以选择(ab)use the fact that read will remove leading and trailing spaces

^{pr2}$

在您的示例中,您基本上希望删除所有空格:

$ echo "${mystring// }"
foo
bar
stack
overflow

不要缩进字符串,而是抑制导致需要缩进的初始换行符。在

mystring="\
foo
bar
stack
overflow"

“here document”功能允许将多行字符串定义为命令的输入:

$ cat <<_EOT_
    Lorem ipsum dolor sit amet,
        consectetur adipiscing elit.
    Morbi quis rutrum nisi, nec dignissim libero.
_EOT_
^{pr2}$

Bash手册section on here documents描述了一个允许在源代码中缩进的选项,并在读取文本时删除它:

Here Documents

[…]

If the redirection operator is <<-, then all leading tab characters are stripped from input lines and the line containing delimiter. This allows here-documents within shell scripts to be indented in a natural fashion.

看起来像这样:

$ cat <<-_EOT_
    Lorem ipsum dolor sit amet,
        consectetur adipiscing elit.
    Morbi quis rutrum nisi, nec dignissim libero.
_EOT_
Lorem ipsum dolor sit amet,
    consectetur adipiscing elit.
Morbi quis rutrum nisi, nec dignissim libero.

问题是它只会去除制表符(U+0009)的缩进,而不是空格。如果您的编码风格禁止在源代码中使用制表符,那么这是一个严重的限制:-(

相关问题 更多 >

    热门问题