简体   繁体   English

如何使用.SH文件脚本替换文本文件中的文本?

[英]How to replace text in text file using .SH file script?

So I want to create a script that takes 3 arguments - path to file, exact word to replace and with what to replace it. 因此,我想创建一个包含3个参数的脚本-文件路径,要替换的确切单词以及替换内容。 How to create such thing? 如何创造这样的东西?

Generally I want6 it to have api like sudo script.sh "C:/myTextDoc.xml" "_WORD_TO_REPLACE_" "WordTo Use" 通常,我希望它具有sudo script.sh "C:/myTextDoc.xml" "_WORD_TO_REPLACE_" "WordTo Use"这样的api。 sudo script.sh "C:/myTextDoc.xml" "_WORD_TO_REPLACE_" "WordTo Use"

您不需要脚本,一个简单的sed就可以了(如果您在cygwin或POSIX兼容操作系统下运行):

sed -i '' 's/_WORD_TO_REPLACE_/WordTo Use/' "C:/myTextDoc.xml"

Something like this? 像这样吗

#!/bin/bash
sed -e "s/$2/$3/g" <$1 >$1.$$ && cp $1.$$ $1 && rm $1.$$

Alternatively, you can use the single command 或者,您可以使用单个命令

sed -i -e "s/$2/$3/g" $1

as Yan suggested. 如严所言。 I generally use the first form myself. 我通常会自己使用第一种形式。 I have seen systems where -i is not supported (SunOS). 我见过不支持-i系统(SunOS)。

This will replace all instances of the second argument with the third, in the file passed as the first. 在作为第一个传递的文件中,这会将第二个参数的所有实例替换为第三个参数。 For example, ./replace file oldword newword 例如,。/ ./replace file oldword newword

红宝石(1.9+)

$ ruby -i.bak -ne 'print $_.gsub(/WORD_TO_REPLACE/,"New Word")' /path/to/file

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

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