Shell 脚本输出缩进

lsc*_*ann 5 linux unix shell format

我想在另一个脚本中调用一个 shell 脚本/应用程序。包含的脚本的每一行都应该缩进 2 个空格。这可能吗?

输出应该是这样的。

I'm the main-scripts' output.
  I'm a second script, called inside the main-script.
  Every line of my output is indented by 2 spaces.
  This is not implemented inside of me, but in the main-script
  as I should also be called outside of the main-script and then
  my output shouldn't be indented.
Thats all from the second script.
Run Code Online (Sandbox Code Playgroud)

这是可能的吗?

gog*_*ors 6

您可以使用sedawk来执行此操作。例如,在您的主脚本中,您可以执行以下操作:

# execute the command and pipe to sed
second-script | sed 's/\(.*\)/  \1/'
Run Code Online (Sandbox Code Playgroud)

上面的sed命令只是在second-script.


Ric*_*ich 6

与 Unix 中一样,有多种选择。

paste

使用paste带有空白 LHS 文件的实用程序,例如:

cat ~/.bashrc | paste /dev/null -
Run Code Online (Sandbox Code Playgroud)

cat命令是第二个脚本的占位符。

paste命令旨在获取两个文件并将它们放在一起,例如:

$ paste file1 file2
file 1 line 1    <TAB>  file 2 line 1
file 1 line two  <TAB>  file 2 line 2
file 1 line 3    <TAB>  file 2 line iii
Run Code Online (Sandbox Code Playgroud)

我上面使用它的方式是使用/dev/nullasfile1STDINas file2,由 指定-。用作输入时,/dev/null返回 NULL 字符。这意味着file2第二个脚本的输出的每一行前面都是 NULL,后跟一个制表符。

您可以更进一步:paste有一个--delimiter选项,但指定两个空格不会给出预期的效果:分隔符 1用于第一列和第二列之间,分隔符 2用于第二列和第三列之间,依此类推。

paste|expand

要获得两个空格的缩进,您可以paste再次使用普通管道通过expand -2:这会将所有制表符变成两个空格:

cat ~/.bashrc | paste /dev/null - | expand -2
Run Code Online (Sandbox Code Playgroud)

这将完全按照您指定的方式运行。

sed或者awk

另一种方法是使用sedor awk

cat ~/.bashrc | sed 's/^/  /'
Run Code Online (Sandbox Code Playgroud)

这将搜索行的开头 (" ^"),并替换或真正插入一对空格。

cat ~/.bashrc | awk '{printf "  %s\n",$0}'
Run Code Online (Sandbox Code Playgroud)

这将获取每个整行 (" $0") 并将其格式化为printf,使用两个空格的格式说明符,后跟要打印的字符串,后跟换行符。


请记住,上述所有命令都可以消除cat管道的一部分,即paste /dev/null ~/.bashrc, 或paste /dev/null ~/.bashrc|expand -2,同样sed 's/^/ /' ~/.bashrcawk '{printf " %s\n",$0}' ~/.bashrccat首先在管道中使用通常被视为初学者的错误。