LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   sed command to global change if it match some pattern (https://www.linuxquestions.org/questions/linux-newbie-8/sed-command-to-global-change-if-it-match-some-pattern-4175542021/)

susanau 05-08-2015 06:17 PM

sed command to global change if it match some pattern
 
This is what I have
FINPXXX
FOLLOWS FINPJOB99
CALENDAR1 FINP456
CALENDAR2 FINP374
CALENDAR3 FINPOE9

End result I want is
FINPXXX
FOLLOWS FINPJOB99
CALENDAR1 FIND456
CALENDAR2 FIND374
CALENDAR3 FINDOE9

I have 3 commands
sed 's/CALENDAR1 FINP/CALENDAR1 FIND/g'
sed 's/CALENDAR2 FINP/CALENDAR2 FIND/g'
sed 's/CALENDAR3 FINP/CALENDAR3 FIND/g'

I cannot just do sed 's/FINP/FIND/g' because there are a lot of 'FINP' pattern in the file I need to keep.

The problem I have is I have a lot of files, and I have to go thru each file to find out how many CALENDAR# pattern I have. Is there a better way to do the sed command? I tried this
sed 's/CALENDAR. FINP/CALENDAR. FIND' But it replaces all CALENDAR# to CALENDAR.

Thank you.

syg00 05-08-2015 09:20 PM

Use regex - sed supports character classes
Code:

sed -r 's/(CALENDAR[[:digit:][:space:]]+FIN)P(.*)/\1D\2/' cal.txt
No need for global change unless there is more than one occurrence per record - doesn't harm if you leave it in.

grail 05-09-2015 02:37 AM

An alternative which assumes 'CAL' is always at the start of the lines we want to change:
Code:

sed '/^CAL/s/FINP/FIND/' file

susanau 05-11-2015 03:57 PM

Thank you. It works!

grail 05-12-2015 02:57 AM

Remember to mark as SOLVED once you have a solution.


All times are GMT -5. The time now is 03:27 PM.