0

I want to extract a number from a string and use that number for future calculations

while IFS= read line ; do  

  if [[ "$line" == Content-Length* ]]
  then
  size=$(echo "$line" | awk '{print $2}')   
  echo "$size"
  let size=$size+1  
  echo "$size"
  break
  fi    
done <files

files has the line

Content-Length: 4806

but output looks like this

4806
+1")syntax error: invalid arithmetic operator (error token is "
4806

i tried this for more than 5 hrs but could find why is this happening .can some one tell me why

4
  • 1
    I ran your script and it ran fine. Commented Oct 18, 2013 at 21:04
  • 2
    The file you are parsing has DOS line endings, which cause $line to end with a carriage return (\r). This carriage return winds up in the value of size, which the let statement chokes on. Notice the odd error where the text following $size appears at the beginning of the error message, not the end. The actual error token is 4806\r+1. Commented Oct 18, 2013 at 21:10
  • Thanq @chepner but can u tell me how can i solve that problem Commented Oct 18, 2013 at 21:13
  • 1
    (Minor correction to my previous comment, the error token is \r+1. Too late to edit the comment). Commented Oct 18, 2013 at 21:16

2 Answers 2

2

You can take advantage of the fact that Content-Length: 4806 is actually a space-delimited pair of strings.

while read -r field value; do
    if [ "$field" = "Content-Length" ]; then
        echo "$size"
        echo "$((size+1))"
    fi
done < files

To solve the problem of DOS line endings, either run the file through dos2unix or some other tool to fix the line endings, or trim the carriage return using

size=${size%.}

which will remove the final character of size from its value. Fixing the file, rather than coding around it, is recommended.

Sign up to request clarification or add additional context in comments.

Comments

0

you can replace:

let size=$size+1

to

let size=$[$size+1]

or

let size=$[size+1]

or

let size++

or

let size=`expr $size + 1`

All example run fine on ubuntu 13.04 and you example too.

1 Comment

In Ubuntu you can remove the let and just use ((size++)). And you should not use back tics `` use parantheses $() like this let size=$(expr $size + 1)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.