title: Counting the number of fields stored in a variable
body: <p>I'm working on a basic file carver and I'm currently stuck on calculate the byte position of the file.</p>
  
  <p>I've worked out that I need a piece of code to perform the following steps;</p>
  
  <ol>
  <li>Locate the $searchQuery in the variable</li>
  <li>Remove the rest of the string after the $searchQuery is found</li>
  <li>Count the number of fields that now exist within the variable</li>
  <li>Minus 2 from this variable to take into account the Hex Offset and the $searchQuery itself</li>
  <li>Then multiply the answer by two to get the correct byte count</li>
  </ol>
  
  <p>An example of this would be;</p>
  
  <ol>
  <li>Locate "ffd8" within "00052a0: b4f1 559c ffd8 ffe0 0010 4a46 4946 0001"</li>
  <li>Variable is updated to "00052a0: b4f1 559c ffd8"</li>
  <li>$fieldCount is assigned the value of "4"</li>
  <li>$fieldCount=((fieldCount-2))</li>
  <li>$byteCount=((fieldCount*2))</li>
  </ol>
  
  <p>I have a basic idea of how to do everything but count the number of fields in the variable. For example, how would I count how many fields there are in the variable until the $searchQuery is found? And similarly, how do I count the number of fields once I've removed the unnecessary part of the string?</p>
  
  <p>After locating the $searchString with grep I have no idea how to proceed. My current code looks like this;</p>
  
  <pre><code>#!/bin/bash
  #***************************************************************
  #Name:          fileCarver.sh
  #Purpose:       Extracts files hidden within other files
  #Author:        
  #Date Written:      12/01/2013
  #Last Updated:      12/01/2013
  #***************************************************************
  
  clear
  
  #Request user input
  printf "Please enter the input file name: "
  read inputFile
  printf "Please enter the search string: "
  read searchString
  
  #Search for the required string
  searchFunction()
  {
      #Search for required string and remove unnecessary characters
      startHexOffset=`xxd $1 | grep $2 | cut -d":" -f 1`
      #Convert the Hex Offset to Decimal
      startDecOffset=$(echo "ibase=16;${startHexOffset^^}" | bc)
  }
  
  searchFunction $inputFile $searchString
  
  
  exit 0
  </code></pre>
  
  <p>Thanks for the help!</p>