Stripping all content but an integer

Hello! I have content in a log file that consists of a lot of spaces before and after a 3 digit integer which I need to strip out before I can use the file. The number of digits can change. When I had my logic in a 'for' loop and could output into another file, it was fine. but it turns out that I will only have 1 line now and don't need the for loop. I have tried a lot of different logic for grepping using the 'x' switch and it didn't work outside of the loop. I tried the E switch as well. This is what I had that worked inside of a for loop, any ideas on how to strip the spaces from the integer? I tried taking just that one line below with the grep, I tried using 'cat' instead of 'echo', nothing worked:

SQL_COUNT=`cat ${LOGPATH}/sql_count.log`
NUM_LOG=${LOGPATH}/num.log

for x in ${SQL_COUNT}
do
echo $x | grep -x '[0-9]*'
done > ${NUM_LOG}

Use tr:

 echo "       1234567         " | tr -dc '[0-9]'

Or in your case try

cat filename | tr -dc '[0-9]'

Worked perfectly, thanks!

The solution:

... | tr -dc '[0-9]'

also removed he carriage return at the end of each line.

Here is another solution, keeping the carriage return:

echo "       1234567         " | sed 's/ //g'
sed 's/ //g' input_file

A cruel way ! :slight_smile:

echo "       1234567         " | awk '{ print $0 + 0 }'

Yes, I didn't realize that I didn't have the carriage return, then again, I'm too new at this to realize that when my ID prompt listed right after my number that it meant I didn't have a carriage return :). Thanks!

I'm working with a ksh script on a windows box calling a sendmail bat file, now if I can only get it to send me mail! :slight_smile: At least I have the trimmed number to work with, maybe there's something with how I'm manipulating my code - yesterday it worked and I have changed things today...

Thanks again,

tr -dc '[0-9]' < filename

This can be done with just shell builtins...

$ x="       1234      "
$ echo \""$x"\"
"       1234      "
$ ((x=x+0))
$ echo \""$x"\"
"1234"
$

Or (with bash/ksh93):

$ x="       1234      "
$ x="${x//[!0-9]}";echo "$x"
1234

With zsh:

$ x="       1234      "
$ x="${x//[^0-9]}";echo "$x"
1234

If it's all about spaces/tabs etc:

bash:

$ x="       1234      "
$ x=($x)
$ echo "$x"
1234

or (with sh):

$ x="       1234      "
$ set -- $x;x="$1";echo "$x"
1234

If there is only one line in the file, all you need is:

read number < FILE

This stores the first line of the FILE into the variable "number" immaterial of the no. of lines