Operating System - Linux
1819694 Members
3358 Online
109605 Solutions
New Discussion юеВ

grep and replace text in a file

 
SOLVED
Go to solution
MikeL_4
Super Advisor

grep and replace text in a file

I need a way to run a command in a script, that will grep for a parameter, and if fould, replace the entire line where it was found with a new line....

Any ideas on how to accomplish this ?

Thanks
7 REPLIES 7
Tim Nelson
Honored Contributor

Re: grep and replace text in a file

Either awk or sed is the way to go.
Give us and example and we will send some ideas.


Elmar P. Kolkman
Honored Contributor

Re: grep and replace text in a file

It will become something like:
awk '// { print "";next}{print}'
Every problem has at least one solution. Only some solutions are harder to find.
James R. Ferguson
Acclaimed Contributor

Re: grep and replace text in a file

Hi:

How about?

# perl -pe 's/(.*trigger.*)/something new/' file

Thus, any line in the file containing the string "trigger" is totally replaced with a line that reads "something new".

Regards!

...JRF...


MikeL_4
Super Advisor

Re: grep and replace text in a file

I am checking for PASS_MAX_DAYS, and there are two occurances in the file, one being a comment line which I don't care about, only need to change the actual parameter line..

I've tried these two commands, but the end result is a blank file, which isn't good...

LIN=`/bin/grep -n "PASS_MAX_DAYS" /etc/login.defs | /bin/grep -v "#" | /bin/awk -F : '{print $1}'`
/bin/awk '{if (NR==${LIN}) $0="PASS_MAX_DAYS 30";print}' /etc/login.defs > /etc/login.defs.NEW

MikeL_4
Super Advisor

Re: grep and replace text in a file

A grep of the parameter shows two lines:

12:# PASS_MAX_DAYS Maximum number of days a password may be used.
17:PASS_MAX_DAYS 99999

whish is why I was trying to isolate the 2nd line for the actual line number that needs to be changed....


Thanks
James R. Ferguson
Acclaimed Contributor
Solution

Re: grep and replace text in a file

Hi (again) Mike:

You could find the non-commented line matching the parameter you want and change the value that follows it like this:

# perl -pe 'next if /^\s*#/;s/(PASS_MAX_DAYS\s+)(\d+)\b(.*)/${1}1234${3}/' file

This would find lines (any or all) in your file that constain the string:

PASS_MAX_DAYS

...followed by whitespace (\s) and one or more digits (\d+) like:

PASS_MAX_DAYS 10

...or:

PASS_MAX_DAYS 10 #...change to your taste

...and in this example change the '10' to '1234'

If you want to perform this update in-place and retain a backup copy (*.old) of your file, do:

# perl -pi.old -e 'next if /^\s*#/;s/(PASS_MAX_DAYS\s+)(\d+)\b(.*)/${1}1234${3}/' file

Regards!

...JRF...
MikeL_4
Super Advisor

Re: grep and replace text in a file

ames, Thanks alot, the perl statement worked perfectly...