sed在bash脚本中不起作用

时间:2011-05-30 00:10:36

标签: bash replace sed

我已经搜索了几个小时寻找这个问题的答案,这看起来非常简单......

我有一个bash脚本,我已经简化了,找到了阻止它工作的行,我留下了:

#!/bin/bash
#
sed -i -e "s/<link>/\n/g" /usb/lenny/rss/tmp/rss.tmp

如果我运行此脚本,文件rss.tmp没有任何反应 - 但如果我从终端调用这个完全相同的sed命令,它会按预期进行所有替换。

任何人都知道我在这里做错了什么?

4 个答案:

答案 0 :(得分:1)

基于讨论,问题听起来像是一个cygwin shell问题。 问题是shell脚本可能没有\ r \ n行终止 - 它们需要\ n终止。早期版本的cygwin表现不同。 来自http://cs.nyu.edu/~yap/prog/cygwin/FAQs.html

的Cygwin常见问题解答的相关部分
Q: Mysterious errors in shell scripts, .bashrc, etc


    A: You may get mysterious messages when bash reads
    your .bashrc or .bash_profile, such as
        "\r command not found"
    (or similar).  When you get rid of empty lines, the
    complaints about "\r" disappears, but probably other
    errors remain.  What is going on?

    The answer may lie in the fact that a text file (also
    called ASCII file) can come in two formats:
    in DOS format or in UNIX format. 
    Most editors can automatically detect the formats
    and work properly in either format.
    In the DOS format, a new line is represented by two characters:
    CR (carriage return or ASCII code 13) and LF (line feed or ASCII code 15).
    In the UNIX format, a new line is represented by only
    one character, LF.  When your .bashrc file is read,
    bash thinks the extra character is the name of a command,
    hence the error message.

    In Cygwin or unix, you can convert a file INFILE in DOS format
    to a file OUTFILE in Unix format by calling:

        > tr -d '\15'  OUTFILE

    NOTE:
    If you now compare the number of characters in INFILE and OUTFILE,
    you will see that the latter has lost the correct
    number of characters (i.e., the number of lines in INFILE):

        > wc INFILE OUTFILE

答案 1 :(得分:0)

请尝试使用它:

sed -i -e "s/\<link\>/\n/g" /usb/lenny/rss/tmp/rss.tmp

答案 2 :(得分:-1)

您需要提供输出文件,否则结果将仅显示在屏幕上。

sed -e 's/<link>/\n/g' /usb/lenny/rss/tmp/rss.tmp > /usb/lenny/rss/tmp/output.tmp

答案 3 :(得分:-4)

将文件提供给您使用“&lt;”的命令,而制作文件则使用“&gt;”据我所知,sed用作文本格式化程序而不是编辑器 也许这样的事情应该有用

cat < /usb/lenny/rss/tmp/rss.tmp | sed -i -e "s/<link>/\n/g" > /usb/lenny/rss/tmp/rssedit.tmp

cat获取文件并使用sed编辑它,输出转到rssedit.tmp

检查rssedit.tmp是否有你想要的东西

如果确实如此,且只有

你的下一行 应该是

mv /usb/lenny/rss/tmp/rssedit.tmp /usb/lenny/rss/tmp/rss.tmp 

将使用原始内容替换为1,并将其重命名为原始