So I'm trying to write a script that will take any given CSV file, with a non-fixed number of rows/columns, and parse each field as an input for another part of the script.
Script should take each field, and store it in a variable named, let's say f{var} where {var} is the number variable it is. These variables will later need to be parsed to recognize IP addresses from IP addresses+CIDR (x.x.x.x/yy). However, before even getting to figuring out how to do variable amounts of variables, I am having a few issues (pretty new to scripting).
I've been experimenting with some of the solutions found on this and other sites, but the behavior I'm observing when testing doesn't seem to match what's described. For example, grep -o "...$"
(to pull the last 3 characters) seems to return only 2 characters not 3 in some cases. Both lines in my test csv are 4 columns of IP addresses.
I ran something like this
input="/home/admin/parsetest.cvs"
while IFS=',' read -r f1 f2 f3 f4
do
echo "$f1 $f2 $f3 $f4"
done < "$input"
But it only produced a single line, rather than echo
'ing both lines to STDOUT
. Looking at it with -xv on, it looks like it reads the first line, echo's it, checks IFS, reads again, and then terminates. I'm fairly certain I'm doing something wrong, but I'm not sure what.
[Expert@LabFW01:0]# ./csvparse.sh
#!/bin/bash -xv
echo "IFS delimiter set to ,"
+ echo 'IFS delimiter set to ,'
IFS delimiter set to ,
input="/home/admin/parsetest.csv"
+ input=/home/admin/parsetest.csv
while IFS=',' read -r f1 f2 f3 f4
do
echo "$f1 $f2 $f3 $f4"
done < $input
+ IFS=, + read -r f1 f2 f3 f4 '
echo '192.168.1.1 192.168.1.2 192.168.1.3 192.168.1.4 192.168.1.1 192.168.1.2 192.168.1.3 192.168.1.4
+ IFS=, + read -r f1 f2 f3 f4