awk with variables in condition and in output redirection file

5,050

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"
Share:
5,050

Related videos on Youtube

MariaK
Author by

MariaK

Updated on September 18, 2022

Comments

  • MariaK
    MariaK almost 2 years

    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
    
    • vfbsilva
      vfbsilva over 9 years
      @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.
    • MariaK
      MariaK over 9 years
      @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
    MariaK over 9 years
    Thanx !! Both working very quickly ! ;-)
  • MariaK
    MariaK over 9 years
    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!