如何让 bash "eat" 字符串中所有行共有的缩进字符?
How do I have bash "eat" indentation characters common to all lines in a string?
我在 shell 变量中有一些多行字符串。字符串的所有行都有至少几个白色 space 字符的未知缩进级别(在我的示例中为 8 spaces,但可以是任意的)。例如,让我们看一下这个示例字符串:
I am at the root indentation level (8 spaces).
I am at the root indentation level, too.
I am one level deeper
Am too
I am at the root again
I am even two levels deeper
three
two
one
common
common
我想要的是一个 Bash 函数或命令来去除常见的缩进级别(这里是 8 spaces)所以我得到了这个:
I am at the root indentation level (8 spaces).
I am at the root indentation level, too.
I am one level deeper
Am too
I am at the root again
I am even two levels deeper
three
two
one
common
common
可以假定此字符串的第一行始终处于此通用缩进级别。最简单的方法是什么?理想情况下,当逐行读取字符串时,它应该可以工作。
您可以使用 awk
:
awk 'NR==1 && match([=10=], /^ +/){n=RLENGTH} {sub("^ {"n"}", "")} 1' file
I am at the root indentation level (8 spaces).
I am at the root indentation level, too.
I am one level deeper
Am too
I am at the root again
I am even two levels deeper
three
two
one
common
common
对于第一条记录 (NR==1
),我们匹配开始处的空格 (match([=13=], /^ +/)
) 并将匹配的长度 (RLENGTH
) 存储到变量 n
.
然后在打印时我们去除 gsub("^ {"n"}", "")
.
中的 n
个空格
我在 shell 变量中有一些多行字符串。字符串的所有行都有至少几个白色 space 字符的未知缩进级别(在我的示例中为 8 spaces,但可以是任意的)。例如,让我们看一下这个示例字符串:
I am at the root indentation level (8 spaces).
I am at the root indentation level, too.
I am one level deeper
Am too
I am at the root again
I am even two levels deeper
three
two
one
common
common
我想要的是一个 Bash 函数或命令来去除常见的缩进级别(这里是 8 spaces)所以我得到了这个:
I am at the root indentation level (8 spaces).
I am at the root indentation level, too.
I am one level deeper
Am too
I am at the root again
I am even two levels deeper
three
two
one
common
common
可以假定此字符串的第一行始终处于此通用缩进级别。最简单的方法是什么?理想情况下,当逐行读取字符串时,它应该可以工作。
您可以使用 awk
:
awk 'NR==1 && match([=10=], /^ +/){n=RLENGTH} {sub("^ {"n"}", "")} 1' file
I am at the root indentation level (8 spaces).
I am at the root indentation level, too.
I am one level deeper
Am too
I am at the root again
I am even two levels deeper
three
two
one
common
common
对于第一条记录 (NR==1
),我们匹配开始处的空格 (match([=13=], /^ +/)
) 并将匹配的长度 (RLENGTH
) 存储到变量 n
.
然后在打印时我们去除 gsub("^ {"n"}", "")
.
n
个空格