V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
Distributions
Ubuntu
Fedora
CentOS
中文资源站
网易开源镜像站
fnmsd
V2EX  ›  Linux

求助 关于 linux shell 编程输出的问题 echo 与 sed 结合使用字符串发生覆盖

  •  
  •   fnmsd · 2015-11-21 21:53:22 +08:00 · 3671 次点击
    这是一个创建于 3089 天前的主题,其中的信息可能已经有所发展或是发生改变。
    写了大概这么个东西,为了读 XML 文件并且加点东西:
    #!/bin/sh
    sed -n 's/.*>\(.*\)<\/name>/\1/p' test.xml|while read line
    do
    echo $line
    echo $line:123456
    done

    结果输出时候单 echo $line 没有问题,但是第二个 echo , 123456 的部分覆盖掉了$line 的开头部分,求各位大大解答如何解决
    6 条回复    2015-11-22 02:18:05 +08:00
    xuyinan503
        1
    xuyinan503  
       2015-11-21 23:03:30 +08:00
    test.xml 啥内容
    fnmsd
        2
    fnmsd  
    OP
       2015-11-21 23:05:15 +08:00
    @xuyinan503
    <root>
    <name>test</name>
    </root>
    xuyinan503
        3
    xuyinan503  
       2015-11-21 23:10:44 +08:00
    xuyinan@xuyinan:~$ cat test.xml
    <root>
    <name>test</name>
    </root>
    xuyinan@xuyinan:~$ cat test.sh
    #!/bin/sh
    sed -n 's/.*>\(.*\)<\/name>/\1/p' test.xml|while read line
    do
    echo $line
    echo $line:123456
    done
    xuyinan@xuyinan:~$ ./test.sh
    test
    test:123456
    xuyinan@xuyinan:~$

    实测 ubuntu 正常
    RickyBoy
        4
    RickyBoy  
       2015-11-21 23:13:59 +08:00
    覆盖掉开头部分什么意思?
    正常应该输出
    test
    test:123456
    Arthur2e5
        5
    Arthur2e5  
       2015-11-22 01:14:34 +08:00
    是不是因为 Windows CRLF 所以被 $line 里的 \r 干了?
    Arthur2e5
        6
    Arthur2e5  
       2015-11-22 02:18:05 +08:00
    echo 之前加一个 `line=${line%$'\r'}` 去掉 CR 就好了。

    其实你完全用不着 sed :

    ```Bash
    while IFS='' read -r -u 4 line; do
    [[ $line =~ <name>(.*)</name> ]] || continue
    printf '%s\n' "${BASH_REMATCH[1]}:123456"
    done
    ```
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3468 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 11:54 · PVG 19:54 · LAX 04:54 · JFK 07:54
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.