如何使用 linux shell 脚本更改文件中的单词

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9063730/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 04:16:43  来源:igfitidea点击:

How to change a word in a file with linux shell script

linuxshelltext-files

提问by Behnam Safari

I have a text file which have lots of lines I have a line in it which is: MyCar on

我有一个有很多行的文本文件,其中有一行是:MyCar on

how can I turn my car off?

我怎样才能关掉我的车?

采纳答案by knittl

You could use sed:

你可以使用 sed:

sed -i 's/MyCar on/MyCar off/' path/to/file

回答by Balaswamy Vaddeman

sed 's/MyCar on/MyCar off/' >filename

more on sed

更多关于 sed

回答by technosaurus

You can do this with shell only. This example uses an unnecessary case statement for this particular example, but I included it to show how you could incorporate multiple replacements. Although the code is larger than a sed 1-liner it is typically much faster since it uses only shell builtins (as much as 20x for small files).

您只能使用 shell 执行此操作。这个例子在这个特定的例子中使用了一个不必要的 case 语句,但我包含它是为了展示如何合并多个替换。尽管代码比 sed 1-liner 大,但它通常要快得多,因为它只使用 shell 内置函数(小文件最多可达 20 倍)。

REPLACEOLD="old"
WITHNEW="new"
FILE="tmpfile"
OUTPUT=""
while read LINE || [ "$LINE" ]; do
    case "$LINE" in
        *${REPLACEOLD}*)OUTPUT="${OUTPUT}${LINE//$REPLACEOLD/$WITHNEW}
";;
        *)OUTPUT="${OUTPUT}${LINE}
";;
    esac
done < "${FILE}"
printf "${OUTPUT}" > "${FILE}"

for the simple case one could omit the case statement:

对于简单的情况,可以省略 case 语句:

while read LINE || [ "$LINE" ]; do
    OUTPUT="${OUTPUT}${LINE//$REPLACEOLD/$WITHNEW}
"; done < "${FILE}"
printf "${OUTPUT}" > "${FILE}"

Note: the ...|| [ "$LINE" ]... bit is to prevent losing the last line of a file that doesn't end in a new line (now you know at least one reasone why your text editor keeps adding those)

注意: ...|| [ "$LINE" ]... 位是为了防止丢失不以新行结尾的文件的最后一行(现在您至少知道一个为什么您的文本编辑器不断添加这些的原因)

回答by user2607061

try this command when inside the file

在文件中尝试此命令

:%s/old test/new text/g

:%s/old test/new text/g