-2

I have a file which contains:

    /home/hedgehog/image_0037.jpg
    /home/hedgehog/image_0048.jpg
    /home/hedgehog/image_0039.jpg
    /home/brain/image_0053.jpg
    /home/brain/image_0097.jpg
    /home/brain/image_0004.jpg

I want to add 0 at the end of the lines containing "/hedgehog/", and want to add 1 at the end of the lines containing "/brain/" like this:

/home/hedgehog/image_0037.jpg 0
/home/hedgehog/image_0048.jpg 0
/home/hedgehog/image_0039.jpg 0
/home/brain/image_0053.jpg 1 
/home/brain/image_0097.jpg 1
/home/brain/image_0004.jpg 1
M. ahmed
  • 53
  • 2
  • 11
  • 2
    What have you tried? This is a pretty straight-forward task, with or without Python. Where is your issue? – John Rouhana Nov 07 '18 at 15:40
  • It does not seem to be very related to Ubuntu to me. Most other OSes can have files too. – Jongware Nov 07 '18 at 15:47
  • I need a command which will add a label such as 0,1,2,3... at the end of the line according to there folder name.different folder images will have different labels. but same folder images will have the same label. – M. ahmed Nov 07 '18 at 16:34
  • I am trying this site https://stackoverflow.com/questions/22159044/how-to-append-a-string-at-end-of-a-specific-line-in-a-file-in-bash – M. ahmed Nov 07 '18 at 16:49
  • Thank you but i am found my answer...https://superuser.com/questions/841187/append-text-at-the-end-of-a-specific-line – M. ahmed Nov 07 '18 at 17:03

2 Answers2

0
# first read the file contents:
with open('input.txt', 'r') as fin:
    lines = fin.readlines()

# then iterate over each line and add 0 or 1 accordingly
modified_lines = []
for line in lines:
    if line.startswith('/home/hedgehog/'):
        line += ' 0'
    elif line.startswith('/home/brain/'):
        line += ' 1'
    modified_lines.append(line)

# finally save your modified lines to a new file
with open('output.txt', 'w') as fout:  
    for line in modified_lines:
        fout.write('%s\n' % line)
0

Quick and easy way of doing it:

    # new data to be written
    new_data = ""
    # open text file
    with open ("input.txt", "r+") as in_file:
      # loop each line
      for line in in_file:
        # remove newline character
        line = line.strip("\n\r")
        if "hedgehog" in line:
          line+=" 0"
        if "brain" in line:
          line+=" 1"
        # create the new version and add it to the new file data
        new_data+=line+"\n"
    # write to the file
    with open ("input.txt", "w+") as out_file:
      out_file.write(new_data)
clearshot66
  • 2,292
  • 1
  • 8
  • 17