Reputation: 179
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
Upvotes: 0
Views: 658
Reputation: 11
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.
Upvotes: 0
Reputation: 531075
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.
Upvotes: 2