con*_*use 2 string bash indentation line-by-line
我在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
Run Code Online (Sandbox Code Playgroud)
我想要的是一个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
Run Code Online (Sandbox Code Playgroud)
可以假设该字符串的第一行始终处于此公共缩进级别.最简单的方法是什么?理想情况下,当逐行读取字符串时它应该工作.
你可以使用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
Run Code Online (Sandbox Code Playgroud)
对于第一个记录(NR==1),我们匹配start(match($0, /^ +/))处的空格,并将match(RLENGTH)的长度存储到变量中n.
然后在打印时我们剥离n空间gsub("^ {"n"}", "").