Robin
Robin

Reputation: 3840

Unix command to search a line in a file and replace it

I am trying to replace Config Files with the UnixCommandline without using an Editor like vi or nano.

An example could be:

ServerAdmin [email protected]

I want to find the first or all lines that start with ServerAdmin and replace them with:

ServerAdmin [email protected]

Is there any command to do something like this? It should be possible with the standart UNIX tools also available in CygWin.

Upvotes: 0

Views: 956

Answers (3)

Mike Bastoon
Mike Bastoon

Reputation: 114

all the previous answers are correct but you can also do this with perl one liner

perl -p -i -e 's/ServerAdmin/ServerAdmin [email protected]/g' your_file_name

Upvotes: 2

paxdiablo
paxdiablo

Reputation: 881103

You can use awk to do this, as per the following transcript:

pax> echo 'xyzzy plugh
ServerAdmin [email protected]
twisty passages' | awk '
    /^ServerAdmin /{$0 = "ServerAdmin [email protected]"}{print}'

xyzzy plugh
ServerAdmin [email protected]
twisty passages

In other words, pipe the file through that awk command. It will find lines beginning with "ServerAdmin<space>" and modify those line before printing them. All lines not matching the pattern will be printed as is.

Obviously that's for your simple case as specified. If it turns out your input format is more complicated, you may need to adjust it but awk should still be up to the task.

And remember, if you want to capture the output to a new file rather than standard output, use:

awk 'above awk command goes here' currentFile >newFile

Upvotes: 1

John Zwinck
John Zwinck

Reputation: 249093

sed -i 's/^ServerAdmin .*$/ServerAdmin [email protected]/' in-filename

Upvotes: 5

Related Questions