I have this csv file (sample.csv) which looks like:
variable,value
var1,/value/of/var1/which/is/path
I need to parse/read this csv using tcsh script. I am trying to compare current value of environment variable var1 with value given in this csv file.
something like:
if( current value of $var1 == /value/of/var1/which/is/path) then
echo "Value matches"
else
echo "value does not match with current value"
You can loop over a file like so:
foreach line ( `cat a.csv` )
set field1 = `echo "$line" | cut -d, -f1`
set field2 = `echo "$line" | cut -d, -f2`
if ( "$field1" == "var1" ) then
echo "Match -> $field1 $field2"
else
echo "No match -> $field1 $field2"
endif
end
The foreach
loop will loop over the file line-by-line. Inside the loop, you use the cut
command to split the line by the ,
delimiter. You can can check these variables with an if
statement.
NOTE: If this is a new script, you probably don't want to use tcsh. tcsh is an old shell, and has many dangerous and ugly corners. You probably want to use a Bourne shell (/bin/sh
or bash
), or perhaps better yet, a "real" programming language like Python or Ruby. Parsing CSV files is not always easy (quoting styles and such differ), and both Python and Ruby have excellent csv parsing modules which handle all of this for you.