本文介绍了我怎么有庆典"吃"常见的字符串中的所有行缩进字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个shell变量的一些多行字符串。该字符串的所有行具有至少有一些空白字符的一个未知的缩进级别(8位在我的例子,但也可以是任意的)。让我们来看看下面这个例子字符串,例如:

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

我要的是一个Bash的功能或命令,去除压痕的普通级(这里8个空格),所以我得到这样的:

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.

推荐答案

您可以使用 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 ),我们一致在启动空间(匹配($ 0 / ^ + /)),并储存在比赛的长度( RLENGTH )到一个变量 N

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.

然后在打印过程中,我们剥离 N GSUB空间(^ {N},)

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

这篇关于我怎么有庆典"吃"常见的字符串中的所有行缩进字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 10:11