Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing contents of a file through shell script

Tags:

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 

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 

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

like image 450
user2031888 Avatar asked Feb 01 '13 09:02

user2031888


People also ask

How do you overwrite a file in Unix?

Usually, when you run a cp command, it overwrites the destination file(s) or directory as shown. To run cp in interactive mode so that it prompts you before overwriting an existing file or directory, use the -i flag as shown.

How do I change the content of a shell script?

Find and replace text within a file using sed command The procedure to change the text in files under Linux/Unix using sed: Use Stream EDitor (sed) as follows: sed -i 's/old-text/new-text/g' input.txt. The s is the substitute command of sed for find and replace.

How do I replace text in a file in bash?

To replace content in a file, you must search for the particular file string. The 'sed' command is used to replace any string in a file using a bash script. This command can be used in various ways to replace the content of a file in bash. The 'awk' command can also be used to replace the string in a file.


1 Answers

How about something like:

#!/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 

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.

like image 117
Chris Seymour Avatar answered Oct 04 '22 20:10

Chris Seymour