Run a bash script from an R script

23,996

The way to debug this is to use cat to test whether your character string has been escaped correctly. So:

  1. Create an object x with your string
  2. Carefully escape all the special characters, in this case quotes and backslashes
  3. Use cat(x) to inspect the resulting string.

For example:

x <- 'samtools view filename.bam | awk \'{OFS="\\t"; print ">"$1"\\n"$10}\' - > filename.fasta'

cat(x)
samtools view filename.bam | awk '{OFS="\t"; print ">"$1"\n"$10}' - > filename.fasta

If this gives the correct string, then you should be able to use

system(x)
Share:
23,996
cianius
Author by

cianius

Updated on February 21, 2020

Comments

  • cianius
    cianius about 4 years

    So I have this programme samtools that I want to use from cmd line, converting one file to another. It works like this:

    bash-4.2$ samtools view filename.bam | awk '{OFS="\t"; print ">"$1"\n"$10}' - > filename.fasta
    

    As I want to automate this, I would like to automate it by using an R script. I know you can use system() to run an OS command, but I cannot get it to work by trying

    system(samtools view filename.bam | awk '{OFS="\t"; print ">"$1"\n"$10}' - > filename.fasta)
    

    Is it just a matter of using regexes to get rid of spaces and stuff so the comma nd argument system(command) is readable? How do I do this?

    EDIT:

    system("samtools view filename.bam | awk '{OFS="\t"; print ">"$1"\n"$10}' - > first_batch_1.fasta") Error: unexpected input in "system("samtools view filename.bam | awk '{OFS="\"

    EDIT2:

    system("samtools view filename.bam | awk '{OFS=\"\t\"; print \">\"$1\"\n\"$10}' - > filename.fasta")

    awk: cmd. line:1: {OFS="    "; print ">"$1"
    awk: cmd. line:1:                         ^ unterminated string
    awk: cmd. line:1: {OFS="    "; print ">"$1"
    awk: cmd. line:1:                         ^ syntax error
    > 
    

    EDIT3: And the winner is:

    system("samtools view filename.bam | awk '{OFS=\"\\t\"; print \">\"$1\"\\n\"$10}' -> filename.fasta")
    
  • cianius
    cianius almost 12 years
    Yes, I need to learn how to debug this myself. Thanks Andrie!
  • Muhammad Usman Saleem
    Muhammad Usman Saleem about 7 years
    @Andrie i have a bash script safe in"c:/test" folder with nametest.sh . I want to call this bash script in r code. I try thissystem command but getting an error dear will you help me?