Hi everyone
This is something I have always managed to get around, rather laboriously and I'm sure it can be done...

I need to search for a line in a file which matches a pattern, and replace that line with another line - and I need to place this into a script so that it is automated. Interactively this takes 1 minute using vi, but I need to put this into a script.

Does anyone have an idea how to do this?


This can be done with PERL is one line.

How about using sed?

cat file|sed 's/old pattern/new pattern/g' >new_file

You can use sed to do a lot of editing "automatically"
strip off leading blanks on a line: 's/^ *//g'
strip off trailing blanks on a line: 's/ *$//g'
delete blank lines : '/^$/d'

you can use regular expressions as well as specific strings.

I think we mistaken alwayslearningunix's actual problem. What kornshellmaven provide is to change the "searching pattern" with "newpattern" throughout the document. but what alw* need is to find the specific pattern in a line, if it exists in that line then replace entire line with a new line(not just the "searching pattern") Right alw*?. I am also curious to know how to do that. :smiley:

I could accomplish this with a perl script. but not a one liner :frowning:

PS: kornshellmaven you don't need to use "cat" there(recalls Pxt's statement). sed 's/old pattern/new pattern/g' file >new_file

Here's a perl one-liner:

perl -n -i.bak -e 'if (/pattern/) { print "new text\n"; } else { print; }' inputfile

This will edit the file named "inputfile" in place, and create a backup (unmodified) called inputfile.bak.
Also note that it will modify _every_ line that contains the pattern. You can do the first match only by adding a little extra logic.

Thanks PxT that is exactly what I needed, yes mib you understood my problem perfectly, sorry if I wasnt clear.