0

I'm reading a gzipped csv file with Bash. I'm able to get the rowcount using zgrep but when I store that rowcount value in a variable, I think the carriage return character is also being stored. So instead of 10, the variable stores 10\r.

When I echo the variable, it looks like a number, and I can't see the carriage return character.

I'm trying to do some math on the variable by comparing it to another variable that stores an integer, which is why this is throwing an error.

How do I remove the carriage return character?

The top answer here seems relevant, but I can't figure out what done is and how to apply it to my situation

This is the function that returns a file's row count: campaignFileRowCount=$(zgrep -w "campaign"$today".csv.gz" rowcountfile_"$today".csv.gz | cut -d, -f2)

Then when I try to do this echo $((campaignFileRowCount - 0)), I get the error ")syntax error: invalid arithmetic operator (error token is "

Community
  • 1
  • 1
simplycoding
  • 2,770
  • 9
  • 46
  • 91

1 Answers1

1

Method 1

Replace:

campaignFileRowCount=$(zgrep -w "campaign"$today".csv.gz" rowcountfile_"$today".csv.gz | cut -d, -f2)

with:

campaignFileRowCount=$(zgrep -w "campaign"$today".csv.gz" rowcountfile_"$today".csv.gz | tr -d '\r' | cut -d, -f2)

The command tr -d '\r' will remove all occurrences of carriage-return from the output.

Method 2

Remove trailing carriage returns using the command (bash required):

campaignFileRowCount=${campaignFileRowCount%%$'\r'}

This is an example of suffix removal. The shell removes from the end of campaignFileRowCount anything that matches the pattern shown following the %%.

John1024
  • 109,961
  • 14
  • 137
  • 171