2

I would please like some help with this command because I didn't find anything in documentation that can cover everything I want.

I have some variables that are global, so I would prefer to keep them out of awk.

    chr="chr10"
    inpfile="exome.bed"
    outfile="exons_chr.bed" -> which should be composed according to chr,
                               so: "exons_" $chr ".bed"

and I want to apply awk in a general form,so that, for any "chr" input by user and any "infile", I could have a one-line command to just create an output according to following condition:

    awk '$1=="$chr" $infile > "exons_"$chr".bed"

So, I also want to compose the output filename each time. When I run it with specific values it works. How can I make it work with variables, to be more general,so that I can use it in a script ?

Is there a way to do it in more lines maybe, like :

    awk ' { if ($1=="$chr") -> copy lines to outfile }' infile
  • @Can you please provide some cod snippets of what are you doing like: Sample input, sample transformation, sample output? It is not clear for me what are you doing atm. – vfbsilva Mar 18 '15 at 13:39
  • @vfbsilva : I wanted to extract the lines of my Infile according to their first column which would be "chr10" or another "chr[1,2 etc] and save it to another file directly. But the syntax of awk with the variables as input was confusing me! Janis response is just what I needed ! :-) – MariaK Mar 19 '15 at 15:13
3

You have various options...

To pass shell variables to awk and use them in string comparison and let the shell create the file:

awk -v chr="$chr" '$1==chr' "$infile" > "exons_${chr}.bed"

To additionally let awk do the output into the file:

awk -v chr="$chr" '$1==chr { print > "exons_" chr ".bed" }' "$infile"
  • Thanx !! Both working very quickly ! ;-) – MariaK Mar 19 '15 at 15:13
  • On the same way but little more complex, I want to use while loop and & awk inside with variables in awk,as before. I opened a new Question for this : [ unix.stackexchange.com/questions/191400/… ], so @Janis, I would appreciate your help again, if you could! – MariaK Mar 20 '15 at 11:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.