NonClockworkChen
V2EX  ›  问与答

请教 bash 替换字符问题

  •  
  •   NonClockworkChen · Dec 1, 2019 · 2242 views
    This topic created in 2376 days ago, the information mentioned may be changed or developed.
    输入:foo="Mike is ";bar=${foo/ /|};echo $bar
    输出:Mike|is
    上面是想要的效果。
    如果把 Mike is 保存在 voc4.txt 文件里。(一行保存一个单词)
    输入:foo="$(< voc4.txt)";bar=${foo/ /|};echo $bar
    输出:Mike is
    就没替换了,为什么?不知道哪里细节错了。请教大佬。
    4 replies    2019-12-01 13:10:58 +08:00
    df4VW
        1
    df4VW  
       Dec 1, 2019   ❤️ 1
    你这不是逗我么兄弟

    一行一个单词,那你哪里来的空格
    uyhyygyug1234
        2
    uyhyygyug1234  
       Dec 1, 2019
    a@master:~# cat voc4.txt
    Mike is
    a@master:~# foo="$(< voc4.txt)";bar=${foo/ /|};echo $bar
    Mike|is


    我这可以啊
    NonClockworkChen
        3
    NonClockworkChen  
    OP
       Dec 1, 2019
    @uyhyygyug1234 你不是一行一个单词,是一行两个单词吧。
    用 bash 的 pattern matching,我感觉是没法处理多行的,我现在用了 tr 命令来解决。
    zbinlin
        4
    zbinlin  
       Dec 1, 2019
    bar=${foo/$'\n'/|}
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5332 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 46ms · UTC 09:15 · PVG 17:15 · LAX 02:15 · JFK 05:15
    ♥ Do have faith in what you're doing.