user1007742
user1007742

Reputation: 571

copy the entries of a file within the file using awk in unix

i have a file and would like to copy some entries that satisfy certain conditions. For example

myfile
chr1 a b c
chr2 a b c
chr3 x y z

I would like to copy lines whose first column starts with chr1 and i want to copy it n times.

myfile
chr1 a b c
chr1 a b c
chr1 a b c
chr2 a b c
chr3 x y z

Upvotes: 1

Views: 190

Answers (3)

glenn jackman
glenn jackman

Reputation: 247002

Given your comments in the berdario answer, I'd write:

awk '
  NR == FNR {
    cond[$1] = $2
    next
  }
  $1 in cond {
    for (i=1; i<cond[$i]; i++) print
  }
  { print }
' conditions filename

Upvotes: 0

berdario
berdario

Reputation: 1860

Something like this would be fine?

awk '{if ($1 == "chr1"){print; print;} print;}'

It will print 2 more times the lines that start with chr1

...and with a for loop:

awk '{if ($1 == "chr1"){ for(i=1;i<=2;i++){ print; } } print;}'

ok, this should be it

#!/usr/bin/awk -f

BEGIN{
    while ((getline < "conditions") > 0){
        cond[$1] = $2
    }
}
{
    print;
    for (i=0; i<cond[$1]; ++i){
        print;
    }
}

given a file named "conditions" like this:

chr1 5
chr2 3

and your example (with chr1, chr2 etc on different lines) as an input

it'll print the chr1 line 6 times, the chr2 line 4 times and the chr3 line 1 time

Upvotes: 0

rob mayoff
rob mayoff

Reputation: 385830

awk -v chr1=a -v n=3 '{ print; } substr($0,0,1) == chr1 { for (i = 0; i < n; ++i) print; }'

Upvotes: 1

Related Questions