title: passing command line arguments to awk in shell script
body: <h1>Background information:</h1>
  
  <p>I am trying to write a small shell script, which searches a pattern (string) in a .fas-file and prints the line and position, where the pattern was found. The following code snippet works, when I call the shell script:</p>
  
  <h2>Script (search.sh):</h2>
  
  <pre><code>#!/bin/bash
  
  awk 's=index($0, "CAATCTCC"){print "line=" NR, "start position=" s}' 100nt_upstream_of_mTSS.fas 
  </code></pre>
  
  <h2>Command line call:</h2>
  
  <pre><code>$ ./search.sh
  </code></pre>
  
  <h1>First problem:</h1>
  
  <p>When I change the script to:</p>
  
  <pre><code>awk 's=index($0, "CAATCTCC"){print "line=" NR, "start position=" s}' 
  </code></pre>
  
  <p>and do the following command line call in my bash:</p>
  
  <pre><code>$ ./search.sh 100nt_upstream_of_mTSS.fas
  </code></pre>
  
  <p>"nothing" happens (something is running, but it takes way too long and no results come up, so terminate the process).</p>
  
  <h1>Worth to know:</h1>
  
  <ul>
  <li>I am in the directory, where search.sh is located</li>
  <li>the file 100nt_upstream_of_mTSS.fas is located there, too</li>
  <li>search.sh is executable</li>
  </ul>
  
  <p>I might be "screen blind", but I can't find the reason, why I am unable to pass a command line argument to my script.</p>
  
  <hr>
  
  <h1>Solution - see comments</h1>
  
  <h1>Note: Only the first occurence of the pattern in a line is found this way.</h1>
  
  <hr>
  
  <h1>Second problem:</h1>
  
  <p>Furthermore, I would like to make the motif (the string) I search for variable. I tried this:</p>
  
  <h2>Script:</h2>
  
  <pre><code>#!/bin/bash
  FILE=$1
  MOTIF=$2
  awk 's=index($0, "$MOTIF"){print "line=" NR, "start position=" s}' "$FILE"
  </code></pre>
  
  <h2>Command line call:</h2>
  
  <pre><code>$ ./search.sh 100nt_upstream_of_mTSS.fas CAATCTCC
  </code></pre>
  
  <p>Idea: First command-line argument worked and was substitued correctly. Why is the second one not substituted correctly?</p>
  
  <h1>Solution so far:</h1>
  
  <h2>Script:</h2>
  
  <pre><code>#!/bin/bash
  file=$1
  awk -v s="$2" 'i=index($0, s){print "line: " NR, "pos: " i}' "$file"
  </code></pre>
  
  <h2>Testing:</h2>
  
  <p>Testfile (test.txt):</p>
  
  <p>1 GAGAGAGAGA</p>
  
  <p>2 CTCTCTCTCT</p>
  
  <p>3 TATATATATA</p>
  
  <p>4 CGCGCGCGCG</p>
  
  <p>5 CCCCCCCCCC</p>
  
  <p>6 GGGGGGGGGG</p>
  
  <p>7 AAAAAAAAAA</p>
  
  <p>8 TTTTTTTTTT</p>
  
  <p>9 TGATTTTTTT</p>
  
  <p>10 CCCCCCCCGA</p>
  
  <pre><code> $ ./search.sh test.txt GA
  </code></pre>
  
  <p>will print:</p>
  
  <p>line: 1 pos: 1</p>
  
  <p>line: 4 pos: 2</p>
  
  <p>line: 6 pos: 1</p>
  
  <p>line: 9 pos: 2</p>
  
  <p>line: 10 pos: 9</p>
  
  <p>This script will print line and first match position in the line of only the first character of my pattern. How do I manage to have all results printed and the full pattern being used?</p>