To extract a string from filename and insert it into the file
<p>I want to write a bash script for extracting a string from the file name and insert that string into a specific location in the same file.</p>

<p>For example:
Under <code>/root</code> dir there are different date directories <code>20160201</code>, <code>20160202</code>, <code>20160203</code> and under each directory there is a file <code>abc20160201.dat</code>, <code>abc20160202.dat</code>, <code>abc20160203.dat</code>. </p>

<p>My requirement is that I need to extract the date from each file name first, and then insert that date into the second column of each record in the file.</p>

<p>For extracting the date I am using </p>

<pre><code>f=abc20160201.dat
s=`echo $f | cut -c 4-11`
echo "$f -&gt; $s"
</code></pre>

<p>and for inserting the date iI am using </p>

<pre><code>awk 'BEGIN { OFS = "~"; ORS = "\n" ; date="20160201" ; IFS = "~"} { $1=date"~"$1 ; print  } ' file &gt; tempdate
</code></pre>

<p>But in my <code>awk</code> command the date is coming in the first column. Please let me know what I am doing wrong here.</p>

<p>The file on which this operation is being done is a delimited file with fields separated by <code>~</code> characters.</p>

<p>Or if anybody has a better solution for this, please let me know.</p>