0

I am trying to read file which contains value "0" which is enclosed in double quotes. After this I need to perform decision based on the value like

while read line;do result=$line;done < File.csv
if [ $result -gt 0 ]

then
       echo "Failed"
fi

Now this is giving me error like integer expected. Please help.

Naveed
  • 361
  • 1
  • 7
  • 14
  • You could find libraries in C++ or Python parsing CSV files. Why don't you use one of them? And at least, specify in [EBNF](https://en.wikipedia.org/wiki/Extended_Backus%E2%80%93Naur_form) notation the syntax of valid input. Consider also using [GNU gawk](https://www.gnu.org/software/gawk/) or [GNU guile](https://www.gnu.org/software/guile/) for that, since CSV files are ill defined. – Basile Starynkevitch Jan 12 '21 at 05:53
  • It's not clear why you are comparing `fresult` instead of `result`; is that just a typo, or do you hope for `fresult` to magically contain something? – tripleee Jan 12 '21 at 06:44

1 Answers1

0

Linux is a kernel. The script you show is a shell script.

In the Bourne family of shells, all atomic variables are strings. (In Bash / ksh / etc there are also arrays which are collections of strings.)

To strip quotes from both sides of a string, try this sequence of parameter expansions:

value=${value%\"}
value=${value#\"}

Using shell built-ins will be a lot quicker than using an external process, though each of these should be fairly obvious if you had googled at all before asking:

value=$(echo "$value" | tr -d '"')            # discards " everywhere
value=$(sed 's/^"\(.*\)"$/\1/' <<<"$value")   # Bash specific <<<here string
value=$(awk -v val="$value" 'BEGIN { sub(/^"/, "", val); sub(/"$/, "", val); print val }')

Your loop will read and discard all values in the file, then process whatever was on the last line of the file. I'm guessing you want to process each value inside the loop instead?

while IFS="" read -r line; do
    result=${line%\"}
    result=${result#\"}
    [ $result -gt 0 ] && { echo "Failed" >&2; exit 1; }
done < File.csv

(notice IFS="" and read -r, and printing the error message to standard error instead of standard output) but a much better solution is to use Awk for this (the shell's while read -r is horribly inefficient and usually wrong);

awk '{ sub(/^"/, ""); sub(/"$/, "");
    if (0+$0 > 1) { print "Failed" >>"/dev/stderr"; exit 1 } }' File.csv
tripleee
  • 175,061
  • 34
  • 275
  • 318
  • Thanks using below resolved the issue value=${value%\"} value=${value#\"} – Naveed Jan 12 '21 at 17:26
  • Thanks for the accept, though perhaps it would be better if you unaccept so that this question can be deleted as a redundant duplicate. – tripleee Jan 12 '21 at 17:29