LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Perl replace text in file (https://www.linuxquestions.org/questions/programming-9/perl-replace-text-in-file-802334/)

mwanakenya 04-16-2010 02:00 AM

Perl replace text in file
 
Hi All,

I have a text file in this format

aaa1 bbb1 ccc1 63 ddd1 eee1 fff1 ggg1 12 hhh1 7347
aaa2 bbb2 ccc2 8334 ddd2 eee2 fff2 ggg2 722 hhh2 5623
aaa3 bbb3 ccc3 8925 ddd3 eee3 fff3 ggg3 6232 hhh3 653
aaa4 bbb4 ccc4 13 ddd4 eee4 fff4 ggg4 2442 hhh4 333
aaa5 bbb5 ccc5 4523 ddd5 eee5 fff5 ggg5 2332 hhh5 7823
aaa6 bbb6 ccc6 3434 ddd6 eee6 fff6 ggg6 6522 hhh6 23
aaa7 bbb7 ccc7 5634 ddd7 eee7 fff7 ggg7 422 hhh7 6447

In this I'd like to search for hhh1 and if I get a match delete hhh1 in addition to 7347, search for hhh6, delete hhh6 in addition to 23 alongside it and so on... How do I go about it in perl?

PMP 04-16-2010 02:06 AM

Use sed in case you want to do inplace replacement.

And if perl is the only option.

open a file1 in read mode.
open a file2 in write mode.
Read file1 line by line
Replace if the line contain the matching text.
write the line to file2.
move file1 to file1.bak
move file2 to file1

mwanakenya 04-16-2010 02:09 AM

Thanks, how would I accomplish it using sed?

PMP 04-16-2010 02:12 AM

Have a look at this thread I hope it helps.
http://www.linuxquestions.org/questi...n-file-476382/

For sed please tell your distro

ghostdog74 04-16-2010 02:29 AM

seems like what you don't want is always the last 2nd field onwards, so do this with awk

Code:

awk '$(NF-1)=="hhh1"{$NF=$(NF-1)=""}1' file

mwanakenya 04-16-2010 02:48 AM

In this particular case I have other fields after the "last 2nd field" that I need to retain
eg

aaa1 bbb1 ccc1 63 ddd1 eee1 fff1 ggg1 12 hhh1 7347 jjj1 455 kkk1 74764 ....
aaa2 bbb2 ccc2 8334 ddd2 eee2 fff2 ggg2 722 hhh2 5623 jjj2 66 kkk2 76423 ....

the challenge is once I have matched "hhh1" to expand and remove the numerical field after it

PMP 04-16-2010 03:01 AM

Code:

sed 's#hhh1[ 0-9]\+##g' text.txt
For inplace replacement
Code:

sed -i 's#hhh1[ 0-9]\+##g' text.txt
Make sure you backup your original files before going for an inplace replacement

grail 04-16-2010 03:02 AM

Can we assume the hhhX field will always be in the same spot?

mwanakenya 04-16-2010 03:03 AM

Thanks! Worked like a charm!

PMP 04-16-2010 03:08 AM

Well If you have no more queries on it. Please mark this thread as solved.


All times are GMT -5. The time now is 10:42 PM.