通过shell脚本更改文件的内容 [英] Changing contents of a file through shell script

查看:195
本文介绍了通过shell脚本更改文件的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在哪里,我需要更改文件的内容说xyz.cfg的要求。该文件包含类似的值:

I have a requirement where in I need to change the contents of a file say xyz.cfg. the file contains values like:

group address=127.8.8.8
port=7845
Jboss username=xyz_ITR3

我想在通过shell脚本没有需要改变这个内容并保存文件。更改的内容可以像:

I want to change this content when ever needed through a shell script and save the file. Changed content can look like:

group address=127.8.7.7  
port=7822
Jboss username=xyz_ITR4

我如何能实现通过采取用户输入或以其它方式使用此shell脚本?

How can i achieve this using shell script by taking user input or otherwise?

推荐答案

如何是这样的:

#!/bin/bash

addr=$1
port=$2
user=$3

sed -i -e "s/\(address=\).*/\1$1/" \
-e "s/\(port=\).*/\1$2/" \
-e "s/\(username=\).*/\1$3/" xyz.cfg

其中, $ 1,$ 2 $ 3 是传递给脚本的参数。将文件保存它,如 script.sh ,并确保它可执行搭配chmod + X script.sh 然后就可以运行它,如:

Where $1,$2 and $3 are the arguments passed to the script. Save it a file such as script.sh and make sure it executable with chmod +x script.sh then you can run it like:

$ ./script.sh 127.8.7.7 7822 xyz_ITR4

$ cat xyz.cfg
group address=127.8.7.7
port=7822
Jboss username=xyz_ITR4

这给你的基本结构但是你要想想输入验证等。

This gives you the basic structure however you would want to think about validating input ect.

这篇关于通过shell脚本更改文件的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆