How do I have bash “eat” indentation characters common to all lines in a string?

六月ゝ 毕业季﹏ 提交于 2019-12-10 23:36:05

问题


I have some multi-line string in a shell variable. All lines of the string have an unknown indentation level of at least a few white-space characters (8 spaces in my example, but can be arbitrary). Let's look at this example string for instance:

        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

What I want is a Bash function or command to strip away the common level of indentation (8 spaces here) so I get this:

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

It can be assumed that the first line of this string is always at this common indentation level. What is the easiest way to do this? Ideally it should work, when reading the string line by line.


回答1:


You can use 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

For the 1st record (NR==1) we match spaces at start (match($0, /^ +/)) and store the length of the match (RLENGTH) into a variable n.

Then while printing we strip n spaces in gsub("^ {"n"}", "").



来源:https://stackoverflow.com/questions/33837016/how-do-i-have-bash-eat-indentation-characters-common-to-all-lines-in-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!