PDA

View Full Version : search replace first occurence on each line



monkeyking
August 27th, 2009, 11:08 PM
Hi I got some very long files that looks like



hash nam.id.txt
hash nam2.id.txt
...


And Id like to change the first punctuation on each line to a slash,such that the file would become



hash nam/id.txt
hash nam2/id.txt
...


Note that this is not a normal global search replace.

thanks in advance

Can+~
August 28th, 2009, 12:30 AM
Note that this is not a normal global search replace.

In what sense?


#!/usr/bin/env python

original = open("txtfile.txt", "r")
result = open("outfile.txt", "w")

for line in original:
result.write(line.replace(".", "/", 1))

johnl
August 28th, 2009, 01:00 AM
This is a perfect place for sed.


sed "s/\./\//" input.txt > output.txt

ghostdog74
August 28th, 2009, 07:18 AM
In what sense?


#!/usr/bin/env python

original = open("txtfile.txt", "r")
result = open("outfile.txt", "w")

for line in original:
result.write(line.replace(".", "/", 1))

just for completion, file handles should be closed (explicitly) in the above usage.

monkeyking
August 28th, 2009, 02:44 PM
thanks the sed command is indeed perfect for this,

@can

I was trying to avoid, the first 5 replies beeing a global search replace.


Thanks