0

I have a csv file produced with Python that has the following structure:

Name1,8
Name2,0

I want to extract the index associated to each name and to do so I am using one of the two following methods:

line=`grep "Name1" names.csv | cut -d',' -f2`
line=$(grep "Name1" names.csv | cut -d',' -f2)
echo $line #8

But I'm getting an error once I try to implement the comparison:

if [[ ${line} == 8 ]]; then echo TRUE; else echo FALSE; fi
if [ ${line} == 8 ]; then echo TRUE; else echo FALSE; fi
#FALSE

if [ ${line} -gt 8 ]; then echo TRUE; else echo FALSE; fi
: integer expression expected

Someone knows which is the source of this error and how to effectively retrieve a number from a file for latter comparison?

  • 2
    Your issue has nothing to do with backticks but rather what happens when you run `[ $line -gt 8 ]` with an empty `$line`. `-gt` expects numbers; you give it an empty string. There’s nothing wrong in that error message. – bfontaine Oct 17 '17 at 16:12
  • 1
    I bet your csv file has `\r\n` line endings, and the actual contents of the variable is `"8\r"`. use `od -c names.csv` to check, and `dos2unix` or `sed -i 's/\r$//' names.csv` to fix. – glenn jackman Oct 17 '17 at 16:33
  • @glennjackman I also suspected that and checked if something changed by using dos2unix before running grep. It didn't. I have run od too and there are no \r in the file. –  Oct 17 '17 at 16:42
  • OK, let's look at your cut command: the delimiter is comma, so if there are any trailing spaces in the file, they will be included in the variable value. – glenn jackman Oct 17 '17 at 16:50
  • `printf "$line"|wc -c` will tell you if there are extra chars. – Paul Hodges Oct 17 '17 at 16:52
  • @PaulHodges I just did that. There is one character. –  Oct 17 '17 at 17:22
  • Run the script in debug mode (`-x`) or display the content of the `line` variable: `echo ">$line<"` – Jdamian Oct 17 '17 at 17:44
  • @je_b Did you put the `printf` check in your script, or did you run `line=$(grep ...)` at the command line and check that value? – chepner Oct 17 '17 at 18:02
  • @chepner I did it in the command line. –  Oct 17 '17 at 22:19

0 Answers0