You are here:
Linux101
>
Shell 101
> shell101_loop
Linux Shell 101
Question:
In Shell101 how to write Bash for-loop?
I will expand the above question:
In Shell101 how to write Bash script which has a for-loop, integer variables, silent remove, and backquotes?
In this demo I want to use simple shell syntax to concatenate columns from two CSV files.
#!/bin/bash
# ~ann/forloop_gspc.bash
# This script should work on a CSV file from Yahoo with a for-loop.
# I should cd to the right folder:
cd ~ann
export TKR=GSPC
# Assume that ${TKR}2.csv was just built.
cat ${TKR}2.csv | sed '1d' > ${TKR}3.csv
# head ${TKR}2.csv ${TKR}3.csv
declare -i i mylen
mylen=`cat ${TKR}3.csv|wc -l`
i=1
rm -f ${TKR}4.csv
echo I am busy, please wait ...
for ((i=1;i<=mylen;++i))
do
lhs=`sed -n "${i} p" ${TKR}2.csv`
rhs=`sed -n "${i} p" ${TKR}3.csv`
echo $lhs , $rhs >> ${TKR}4.csv
done
echo I am done, I created ${TKR}4.csv from ${TKR}2.csv and ${TKR}3.csv.
echo Here look:
head ${TKR}4.csv
exit
When I run the above script I see this:
ann@feb ~ $
ann@feb ~ $ ./forloop_gspc.bash
I am busy, please wait ...
I am done, I created GSPC4.csv from GSPC2.csv and GSPC3.csv.
Here look:
Date,Close , 2015-02-20,2110.30
2015-02-20,2110.30 , 2015-02-19,2097.45
2015-02-19,2097.45 , 2015-02-18,2099.68
2015-02-18,2099.68 , 2015-02-17,2100.34
2015-02-17,2100.34 , 2015-02-13,2096.99
2015-02-13,2096.99 , 2015-02-12,2088.48
2015-02-12,2088.48 , 2015-02-11,2068.53
2015-02-11,2068.53 , 2015-02-10,2068.59
2015-02-10,2068.59 , 2015-02-09,2046.74
2015-02-09,2046.74 , 2015-02-06,2055.47
ann@feb ~ $
ann@feb ~ $
So, that is the fifth shell programming demo of shell101.
You are here:
Linux101
>
Shell 101
> shell101_loop
You can ask questions in Dan's Machine Learning Class Forum:
https://groups.google.com/forum/#!forum/dan101
|