LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Software (https://www.linuxquestions.org/questions/linux-software-2/)
-   -   matching a pattern in a file & prefixing a word (https://www.linuxquestions.org/questions/linux-software-2/matching-a-pattern-in-a-file-and-prefixing-a-word-722538/)

shivarajM 04-29-2009 02:11 PM

matching a pattern in a file & prefixing a word
 
Hi,

In my shell script i have to match a patten in a file , if found i have to prefix the entair line by a "word"

eg. pattern = "aaa" prefix= #123
file: bbbb xxx
zzzz aaaa
qqqq kkkk

outPut file: bbbb xxx
#123zzzz aaaa
qqqq kkkk


Waiting your precious reply.....

jschiwal 04-29-2009 02:13 PM

Look into using sed. The -i option will allow you to do inplace editing making changes in the original file.

You might not to do this until your sed command is tested.

esoukenka 05-28-2009 12:47 PM

sed
 
Yes sed is what you want.

Test this on your file

sed -e 's/^aaa/wordaaa/g' ../lyrics

This command will replace all lines starting with aaa to wordaaa. Remove the ^ to do them all.

that will not modify file to do that use the -i option

sycamorex 05-28-2009 01:14 PM

If the replacement needs to take place only in lines containing the pattern 'aaa', you could try the following:
Code:

sed -e '/aaa/ s/^/#123/g' file
It will insert '#123' at the beginning of each line containing the pattern 'aaa'
As it was mentioned before, you need to use the switch -i to actually modify the file.
HTH
edit: hope it's not your homework, is it?


All times are GMT -5. The time now is 03:39 AM.