如何在 bash 中跨多行拆分字符串

How to split string across multiple lines in bash

对我来说,一个持续的烦恼(轻微但持续存在)是我不能(或不知道如何)在 bash 代码中将字符串拆分为多行。我有的是:

    while getopts 'd:h' argv; do
    case "${argv}" in
        d) local target_dir="${OPTARG}" ;;
        h)
           printf "Usage: remove_file_end_strings [ -d <work directory> ] <string to remove>\n"
           return 1
           ;;
    esac

这里看起来不错,因为没有自动换行,但是当限制在 80 个字符和自动换行时看起来很不整洁。 当我想要的是这样的东西时,在 python 或 ruby:

中很简单
    while getopts 'd:h' argv; do
    case "${argv}" in
        d) local target_dir="${OPTARG}" ;;
        h)
           printf "Usage: remove_file_end_strings [ -d <work "
                  "directory> ] <string to remove>\n"
           return 1
           ;;
    esac

我的 google-fu 让我失望了,所以有没有办法在 bash 中实现这一目标,还是我必须继续用力咬一块木头? ta

编辑:我刚刚决定我的次优解决方案:

    while getopts 'd:h' argv; do
    case "${argv}" in
        d) local target_dir="${OPTARG}" ;;
        h)
            printf "Usage: remove_file_end_strings [ -d <work "
            printf "directory> ] <string to remove>\n"
            return 1
            ;;
    esac
done

换行很容易,但在下一行缩进时不引入任何额外的空格或标记边界更难。没有缩进,简单但丑陋:

{
    printf "Usage: remove_file_end_strings \
[ -d <work directory> ] <string to remove>\n"
}

无论好坏,echo 接受的内容更加草率:

echo 'This is my string'   \
     'that is broken over' \
     'multiple lines.'

这将 3 个参数而不是 1 个参数传递给 echo,但是由于参数是用空格连接的,所以结果是一样的。

在您的情况下,当您将整个消息放入格式字符串中时,您可以模拟相同的行为:

printf "%b " 'This is my string'    \
             'that again is broken' \
             'over multiple lines.\n'

尽管当你有一个带有不同插槽的正确格式字符串时,这显然不起作用。

在这种情况下,有黑客:

 printf "I am also split `
        `across %s `
        `lines\n"  \
        "a number of"

将内联文档与 <<- 运算符一起使用:

while getopts 'd:h' argv; do
    case "${argv}" in
            d) local target_dir="${OPTARG}" ;;
            h)
                    cat <<-EOT
                    Usage: remove_file_end_strings [ -d <work directory> ] <string to remove>
                    EOT
    esac
done

查看 man bash 并查找 Here Documents:

If the redirection operator is <<-, then all leading tab characters are stripped from input lines and the line containing delimiter. This allows here-documents within shell scripts to be indented in a natural fashion.

如果需要换行,通过管道输入 sed 命令,该命令将删除字符串之间的制表符:

while getopts 'd:h' argv; do
    case "${argv}" in
            d) local target_dir="${OPTARG}" ;;
            h)
                    cat <<-EOT | sed 's/\t*\([^\t]*\)/ /2g'
                    Usage: remove_file_end_strings [ -d <work \
                    directory> ] <string to remove>
                    EOT
    esac
done