2

我在 shell 变量中有一些多行字符串。字符串的所有行都具有至少几个空白字符的未知缩进级别(在我的示例中为 8 个空格,但可以是任意的)。例如,让我们看一下这个示例字符串:

        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 个空格),所以我得到了这个:

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

可以假设这个字符串的第一行总是在这个公共缩进级别。最简单的方法是什么?理想情况下,它应该在逐行读取字符串时起作用。

4

1 回答 1

6

您可以使用awk

awk 'NR==1 && match($0, /^ +/){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($0, /^ +/)) 处匹配空格并将匹配 () 的长度存储RLENGTH到变量n中。

然后在打印时我们n去掉gsub("^ {"n"}", "").

于 2015-11-20T22:26:45.620 回答