代码之家  ›  专栏  ›  技术社区  ›  stackbiz

如何在bash中将所有换行符替换为“\n”

  •  0
  • stackbiz  · 技术社区  · 1 年前

    我想通过将变量中的所有换行符替换为“ \n “在bash中。

    以下是test.sh:

    #!/bin/bash
    
    hello() {
        local test_string="$(cat <<'END'
    line1
        line2
    line3
    END
        )"
        
        test_string="${test_string/\n/\\n}"
        
        printf "%s" "$test_string"
    }
    
    hello
    

    以下是输出:

    li\ne1
        line2
    line3
    

    以下是预期输出:

    line1\n    line2\nline3
    

    上面的代码中有什么错误,如何修复?

    1 回复  |  直到 1 年前
        1
  •  3
  •   larsks    1 年前

    您需要修复替换表达式:

    test_string="${test_string/\n/\\n}"
    

    首先,你需要 // 为了替换变量中出现的所有模式:

    test_string="${test_string//\n/\\n}"
    

    (请参阅 Parameter Expansion 有关此语法的更多详细信息,请参阅手册页的。)

    其次,普通bash字符串对 \n ;这只是意味着 n ,这就是您看到所显示输出的原因。您需要使用 $'...' 表达式,如下所示:

    test_string="${test_string//$'\n'/\\n}"
    

    (请参阅 QUOTING 手册页的部分。)

    随着这些变化:

    #!/bin/bash
    
    hello() {
        local test_string="$(cat <<'END'
    line1
        line2
    line3
    END
        )"
    
        test_string="${test_string//$'\n'/\\n}"
     
        printf "%s" "$test_string"
    }
    
    hello
    

    您的脚本生成:

    line1\n    line2\nline3
    

    与您的问题无关,但不是使用 cat 和处理替换来设置变量,您可以这样做:

    #!/bin/bash
    
    hello() {
        local test_string
        read -r -d '' test_string <<'END'
    line1
        line2
    line3
    END
        test_string="${test_string//$'\n'/\\n}"
        printf "%s\n" "$test_string"
    }
    
    hello