简体   繁体   English

如何在Linux中从命令行替换文件中的此文本?

[英]How do I replace this text in a file from the command line in Linux?

I have a proxy config file which has the following line: 我有一个代理配置文件,其中包含以下行:

Allow 212.21.3.44

I'd like to replace that IP address portion with my new IP address when it changes. 我希望在更改时用我的新IP地址替换该IP地址部分。 It would probably be easier to just use the line number when searching for it &ndash I don't think that config file will change at all other than that particular setting. 在搜索时可能更容易使用行号&ndash我认为除了特定设置之外,配置文件根本不会改变。

How can I do it from the command line with something like like Perl, sed, etc.? 如何从命令行执行类似Perl,sed等的操作?

如果要使用sed更改特定的行号,可以使用:

sed -i '<line number> s/Allow .*$/Allow <new ip>/g' <filename>

sed -i 's/[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}/my.new.ip.here/' file.txt

-i标志将在适当的位置更改文件(取决于您的发行版/ * nix的风格 - 适用于我的Ubuntu)。

如果行号确实改变了

sed -i '/Allow/s/Allow .*$/Allow <new ip>/' <filename>

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

相关问题 如何在Linux命令行上预替换以下内容 - How do I preg replace the following at linux command line 如何将 output 文本重定向回 Linux 中的命令行? - How do I redirect output text back into the command line in Linux? 如何在Linux或Mac上的文件中一次替换多个文本? - How do I replace multiple text at once in a file on Linux or Mac? 如何从jar文件在Linux命令行中安装yum? - How can I do a yum install in a linux command line from a jar file? 如何使用命令行输入文件在 linux 上运行 C 代码? - How do I run C code on linux with input file from command line? Linux命令用重定向输出中的文本替换文件中的文本 - Linux command to replace text in a file with text from redirected output 如何在 linux 的命令行上使用正则表达式过滤文本文件中以大写字母开头并以正 integer 结尾的行? - How do I filter lines in a text file that start with a capital letter and end with a positive integer with regex on the command line in linux? 当行包含变量时,如何用单个命令替换文件中的一行文本? - How can I replace a line of text in a file with a single command when the line contains a variable? 如何从 linux 命令验证 Erlang 配置文件 - How do I validate an Erlang config file from a linux command 替换文件linux命令中的未知行 - replace unknown line in file linux command
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM