non-uniform string substituion

H

Horacius ReX

Hi,

I have a file with a lot of the following ocurrences:

denmark.handa.1-10
denmark.handa.1-12344
denmark.handa.1-4
denmark.handa.1-56

....

distributed randomly in a file. I need to convert each of this
ocurrences to:

denmark.handa.1-10_1
denmark.handa.1-12344_1
denmark.handa.1-4_1
denmark.handa.1-56_1

so basically I add "_1" at the end of each ocurrence.

I thought about using sed, but as each "root" is different I have no
clue how to go through this.

Any suggestion ?

Thanks in advance.
 
S

Steve Holden

Horacius said:
Hi,

I have a file with a lot of the following ocurrences:

denmark.handa.1-10
denmark.handa.1-12344
denmark.handa.1-4
denmark.handa.1-56

...

distributed randomly in a file. I need to convert each of this
ocurrences to:

denmark.handa.1-10_1
denmark.handa.1-12344_1
denmark.handa.1-4_1
denmark.handa.1-56_1

so basically I add "_1" at the end of each ocurrence.

I thought about using sed, but as each "root" is different I have no
clue how to go through this.

Any suggestion ?

Thanks in advance.

First you have to tell us what characterizes the lines you want to
process. For example, if the only requirement is that they begin with
"denmark.handa" you could say

for line in sys.stdin:
if line.startswith("denmark.handa"):
line = line[:-1]+"_1\n"
sys.stdout.write(line)

regards
Steve
 
7

7stud

Hi,

I have a file with a lot of the following ocurrences:

denmark.handa.1-10
denmark.handa.1-12344
denmark.handa.1-4
denmark.handa.1-56

...

distributed randomly in a file. I need to convert each of this
ocurrences to:

denmark.handa.1-10_1
denmark.handa.1-12344_1
denmark.handa.1-4_1
denmark.handa.1-56_1

Is each one of those a line in the file? Or are those words
distributed throughout the file? If each one is a line, try this:

import os

input = open('data.txt')
output = open('temp.txt', 'w')

for line in input:
if line.startswith('denmark.handa.'):
output.write('%s_1\n' % line.strip())
else:
output.write(line)

os.remove('data.txt')
os.rename('temp.txt', 'data.txt')
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,043
Latest member
CannalabsCBDReview

Latest Threads

Top