简体   繁体   English

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

[英]How to change a word in a file with linux shell script

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?我怎样才能关掉我的车?

你可以使用 sed:

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

You can do this with shell only.您只能使用 shell 执行此操作。 This example uses an unnecessary case statement for this particular example, but I included it to show how you could incorporate multiple replacements.这个例子在这个特定的例子中使用了一个不必要的 case 语句,但我包含它是为了展示如何合并多个替换。 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).尽管代码比 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" ]... 位是为了防止丢失不以新行结尾的文件的最后一行(现在您至少知道一个为什么您的文本编辑器不断添加这些的原因)

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

更多关于 sed

在文件中尝试此命令

:%s/old test/new text/g

Using sed with variables;将 sed 与变量一起使用;

host=$(hostname)
se1=$(cat /opt/splunkforwarder/etc/system/local/server.conf | grep serverName)
sed -i "s/${se1}/serverName = ${host}/g"  /opt/splunkforwarder/etc/system/local/server.conf`

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM