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? |
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 |
Thanks, how would I accomplish it using sed?
|
Have a look at this thread I hope it helps.
http://www.linuxquestions.org/questi...n-file-476382/ For sed please tell your distro |
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 |
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 |
Code:
sed 's#hhh1[ 0-9]\+##g' text.txt Code:
sed -i 's#hhh1[ 0-9]\+##g' text.txt |
Can we assume the hhhX field will always be in the same spot?
|
Thanks! Worked like a charm!
|
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. |