echo的解决方案全局替换

时间:2011-12-20 06:47:02

标签: linux shell sed awk grep

如何将所有ksh脚本中的echo替换为echo -e。 例如:

输入

包含以下行的脚本

echo "\nE-MAILING TO INTERESTED PARTIES....\n"
set echo off
echo -e "\nE-MAILING TO INTERESTED PARTIES....\n"

输出:

我不应该打扰set echo off命令,只更改打印echo命令。如果已将其更改为echo -e,则不应再次替换。我应该一次性替换根目录中的所有脚本。

echo -e "\nE-MAILING TO INTERESTED PARTIES....\n"
set echo off
echo -e "\nE-MAILING TO INTERESTED PARTIES....\n"

3 个答案:

答案 0 :(得分:1)

这应该有效 -

sed 's/^echo "/echo -e "/' filename

<强>测试

[jaypal:~/Temp] cat tmp
echo "\nE-MAILING TO INTERESTED PARTIES....\n"
set echo off
echo -e "\nE-MAILING TO INTERESTED PARTIES....\n"
[jaypal:~/Temp] sed 's/^echo "/echo -e "/' tmp
echo -e "\nE-MAILING TO INTERESTED PARTIES....\n"
set echo off
echo -e "\nE-MAILING TO INTERESTED PARTIES....\n"

findexec

find /path/to/directory/ -type f -name "*.ksh" -exec sed -i"bak" 's/^echo "/echo -e "/' {} \;

答案 1 :(得分:1)

sed '/echo [^-]/s/echo/echo -e/'

寻找echo后跟空格和短划线以外的东西;将echo替换为echo -e。将它循环应用到要更改的文件中。

for file in *.sh
do
    sed '/echo [^-]/s/echo/echo -e/' $file > tmp.$$
    mv tmp.$$ $file
done

答案 2 :(得分:1)

更强大的正则表达式会在任何上下文中寻找echo,而不是-eoff: 由于sed无法在正则表达式中进行查看,因此您必须使用perl

perl -pe 's/echo +(?!((-[A-Za-df-z]|--[a-z-]+) +)*(-e|off))/echo -e/'

这也处理了你可能有(例如)echo -n -e -e的情况,但不是直接在echo之后:你不要我想最终得到echo -e -n -e。另外,如果您(比如说)echo --version,则不需要echo -e --version。上面的正则表达式可以解决这些问题。

INPUT

echo "\nE-MAILING TO INTERESTED PARTIES....\n"
set echo off
echo -e "\nE-MAILING TO INTERESTED PARTIES....\n"
echo -n -e "what happens if the -e is already there?"
echo --help # don't want echo -e --help

输出

echo -e"\nE-MAILING TO INTERESTED PARTIES....\n"
set echo off
echo -e "\nE-MAILING TO INTERESTED PARTIES....\n"
echo -n -e "what happens if the -e is already there?"
echo -e--help # don't want echo -e --help