LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Trying to number every other line and append those numbers to end of line (https://www.linuxquestions.org/questions/programming-9/trying-to-number-every-other-line-and-append-those-numbers-to-end-of-line-803625/)

kmkocot 04-22-2010 06:44 PM

Trying to number every other line and append those numbers to end of line
 
Hi all,

I have a file formatted like this:
Code:

>Contig
ATGCATGCAATGCATGCAATGCACGGATGCAATGCATGCA
>Contig
CAATGCACGGATGCATGCCAATGATGCAATGCAT
>Contig
ATGCCGCAGTCTGACTTGCAACTGCCGTCACAGCTGCA
>Contig
CAATAACGCACGGATGCATGCTACCAATGTATGCAATGCAT

Every odd-numbered line is ">Contig" while the even numbered lines vary but are a DNA sequence of variable length and composition.

I am trying to give each Contig a number such that my output would be:
Code:

>Contig1
ATGCATGCAATGCATGCAATGCACGGATGCAATGCATGCA
>Contig2
CAATGCACGGATGCATGCCAATGATGCAATGCAT
>Contig3
ATGCCGCAGTCTGACTTGCAACTGCCGTCACAGCTGCA
>Contig4
ATGCCGCAGTCTGACTTGCAACTGCCGTCACAGCTGCA

I know this has to be really simple but I can't figure it out. Any suggestions would be greatly appreciated.

Thanks!
Kevin

kbp 04-22-2010 11:18 PM

Code:

#!/usr/bin/perl

use strict;
use warnings;

my @data;
my $match = 1;

open( FH, "<test.txt") or die "Cannot open source";
@data=<FH>;
close(FH);

open( FH, ">test.txt") or die "Cannot open dest";
foreach ( @data ) {
        if ( s/(>Contig)/$1$match/ ) { $match++; }
        print FH;
}

close(FH);


dina3e 04-22-2010 11:35 PM

try this..
Code:

#!/bin/sh
counter=0
for line in `cat file_name.txt`
do
if [ $line = '>Contig' ];then
let counter=$counter+1
echo $line$counter
else
echo $line
fi
done


David the H. 04-22-2010 11:55 PM

I did it this way using awk.
Code:

awk -F "i=1" '{if (/>Contig/){print $0i++} else print}' file

grail 04-23-2010 12:33 AM

Same idea:
Code:

awk '/>/{print $0(++i)}!/>/' file

David the H. 04-23-2010 04:02 AM

Quote:

Originally Posted by grail (Post 3944834)
Same idea:
Code:

awk '/>/{print $0(++i)}!/>/' file

Thank you. I knew it could be shorter, but I couldn't quite work out the syntax. (Parentheses around the pre-increment variable...I should've guessed.)

grail 04-23-2010 07:20 AM

Quote:

Parentheses around the pre-increment variable
Took me a couple of tries ;)

kmkocot 04-23-2010 11:17 AM

Thanks!


All times are GMT -5. The time now is 08:21 AM.