2015-11-20 32 views
2

我在shell变量中有一些多行字符串。字符串的所有行都有一个未知的缩进级别,至少有几个空白字符(在我的例子中是8个空格,但可以是任意的)。让我们来看看比如这个例子字符串:如何让bash“吃”字符串中所有行常见的缩进字符?

 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 

可以假定这个字符串的第一行始终处于这个常用的缩进级别。什么是最简单的方法来做到这一点?理想情况下,它应该工作,逐行读取字符串。

+2

“理想情况下,它应该工作,逐行阅读字符串。”当然,除非第一行总是具有确切的常见缩进,否则在您能够确定“通用缩进”之前,您需要阅读所有行。 – 4ae1e1

回答

5

您可以使用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"}", "")

+1

稍作修改以确保只有空格被吃掉:'awk'NR == 1 && match($ 0,/^+ /){n = RLENGTH} {gsub(“^ {”n“,”n“}”,“ ”,$ 0);打印$ 0}'' –

+0

谢谢,我根据您的评论更新了答案。 – anubhava

相关问题