0

I am totally new to shell scripting. Its my first hands on. I have a script where there are 4 txt files in a path and I am getting the last line from the files which are numbers but when I try to add, it gives "expr:non numeric arguments". My script contains the following script.

    one=filename1.txt
    count1=$(tail -1  $one| cut -c 3-)
    echo $count1
    two=filename2.txt
    count2=$(tail -1 $two| cut -c 3-)
    echo $count2
    three=filename3.txt
    count3=$(tail -1 $three| cut -c 3-)
    echo $count3
    four=filename4.txt
    count4=$(tail -1 $four| cut -c 3-)
    echo $count4
    totalCount=`expr $count1 + $count2 + $count3 + $count4`

The text files are a large text files where the last line is always a footer for example File1.txt has FT001886157, file2.txt has FT002689634, file3.txt has FT002372958, file4.txt has FT001516254 and my output is

    001886157
    002689634
    002372958
    001516254

    expr: non-numeric argument
  • 1
    Use `set -x` to enable tracing so you can see what's actually going on. `echo` isn't suited for debugging -- for example, it doesn't show hidden characters like carriage returns. – Charles Duffy Aug 16 '21 at 14:56
  • (also, `expr` shouldn't be used for math in modern code -- it was obsoleted for that purpose with native math being part of the POSIX sh standard when it was released in 1991 -- but if expr doesn't like the values you have in your variables, `$(( var1 + var2 ))` probably won't like them either) – Charles Duffy Aug 16 '21 at 14:58
  • I have also tried $(( var1 + var2 )) but this too not working – Shrikant Venne Aug 16 '21 at 14:59
  • Use `bc` or `awk`. Note also that many tools treat numbers beginning with `0` as octal. – Barmar Aug 16 '21 at 14:59
  • If you really have numbers too large for the shell to handle natively you'll want to use awk, dc, or bc for math; but it doesn't look like that's your actual problem. – Charles Duffy Aug 16 '21 at 15:00
  • Once again, I'd want to see a trace log from running your script with `set -x` active. – Charles Duffy Aug 16 '21 at 15:01
  • I tried removing the leading zeros as well by `c1=$(echo "$count1" | sed 's/^0*//')` then too it tells its not a number – Shrikant Venne Aug 16 '21 at 15:02
  • 1
    After using set -xv got to know that `\r` is being added – Shrikant Venne Aug 16 '21 at 15:26
  • As you've presumably gathered from the linked duplicate -- `\r` is otherwise known as CR, from the CRLF sequences used as line separators in DOS/Windows text files. Save content as UNIX text files and they're moot. – Charles Duffy Aug 16 '21 at 16:47
  • Re leading zeros, see https://stackoverflow.com/questions/53075017/how-can-i-do-bash-arithmetic-with-variables-that-are-numbers-with-leading-zeroes – Shawn Aug 16 '21 at 16:55
  • 1
    @CharlesDuffy thank you for your set -x answer which gave me the answer to my problem. Successfully removed \r as well by using `c1="${count1/$'\r'/}"` – Shrikant Venne Aug 16 '21 at 19:32

0 Answers0