bash - 与 echo 一样缩进行

标签 bash shell

我在打印文件和一些文字时遇到困难。

例如:

/root/文件包含:

line1
line2
line3

脚本:

#!/bin/bash
echo -en "Printing Line of the file: `cat /root/file`\n"

结果:

Printing Line of the file: line1
 line2
 line3

预期结果:

Printing Line of the file:  line1
                            line2
                            line3

如何获得我想要的输出?

最佳答案

只是狂欢:

( 
    first="Printing Line of the file:"
    IFS=
    read -r line
    printf "%*s %s\n" ${#first} "$first" "$line"
    while read -r line; do 
        printf "%*s %s\n" ${#first} "" "$line"
    done 
) < file
Printing Line of the file: line1
                           line2
                           line3

使用 printf,您可以使用 * 作为字段宽度,然后在参数中提供一个数字。我在子 shell 中运行它,因此更改 IFS 不会影响父 shell。


使用标签实现您的书面目标:

echo "Printing Line of the file: $(awk -v ORS="\n\t\t\t" 1 file)"

关于bash - 与 echo 一样缩进行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34689887/

相关文章:

c++ - 隐藏 sh : -c error messages when calling “system” in c++ Linux

linux - 不可见的终端输出正在破坏脚本

windows - 如何解决 bash 编码问题?

postgresql - 如何在 Ubuntu 16 的 shell 脚本中使用 postgres 用户

linux - 为什么我的 shell 脚本会在这个文件中放入任意数字?

shell - 提取最后一行第n列的值

bash - 如何通过管道传输到 awk 脚本中

Bash - 在变量中保存 $@ 时是空间安全的

linux - 如何安排在几秒钟内定时重启我的服务器?

shell - 如何删除打开 Linux shell 时出现的静态消息?