home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!ferkel.ucsb.edu!taco!lll-winken!sun-barr!cs.utexas.edu!wupost!darwin.sura.net!convex!news.utdallas.edu!corpgate!bnrgate!bcars267!bmdhh243!agc
- From: agc@bmdhh298.bnr.ca (Alan Carter)
- Newsgroups: comp.unix.questions
- Subject: Re: grep for number of character string
- Message-ID: <1992Aug19.134310.19038@bnr.uk>
- Date: 19 Aug 92 13:43:10 GMT
- References: <1992Aug18.140346.3939@nlm.nih.gov>
- Sender: news@bnr.uk (News Administrator)
- Organization: BNR-Europe-Limited, Maidenhead, England
- Lines: 78
- Nntp-Posting-Host: bmdhh298
-
- In article <1992Aug18.140346.3939@nlm.nih.gov>, berman@nlm.nih.gov (Lew Berman) writes:
- |> How can I determine if a value is a string or an integer within a
- |> bourne shell script? For example, if a file exists such that
- |> each line may contain a number (integer) or a string (which can
- |> be alpha-numeric) how do I determine which it is? That is to say,
- |> if I cat the file into an argument and then run this data through a
- |> for loop how do I test each element?
- |>
- |> Example data file:
- |>
- |> 345
- |> 5467
- |> 234
- |> 2
- |> 3
- |> 456
- |> 730
- |> aabbccdd
- |> sffeetr$%^
- |> 4566KKLKLK <- not a number
- |> lij56 <- not a number
-
- Sorry, can't send e-mail. The bit you want to fill in your script is:
-
- #! /bin/sh
- data=`cat $1`
-
- for i in $data
- do
- if echo $i | grep -v "[^0-9]" > /dev/null
- then
- echo "$i is a number"
- fi
- done
-
- Slightly odd logic; if it does not contain any characters that are
- not numeric, then it must be a number. Word of warning though: that
- 'data=`cat $1`' trick could burst the shell variable buffer.
- Better to say:
-
- #! /bin/sh
-
- cat $1 | while read i
- do
- if test ! -z "$i"
- then
- if echo $i | grep -v "[^0-9]" > /dev/null
- then
- echo "$i is a number"
- fi
- fi
- done
-
- and use a pipe. Note the extra check 'if test... fi'. This is needed
- to get the same behaviour, as your original script automagically
- removed blank lines. The pipe flavour doesn't, and they don't contain
- any characters that are not numeric :-)
-
- Or best yet, fire up 1 awk instead of many greps and tests, let it chew
- the file and give the output to you for further processing:
-
-
- #! /bin/sh
-
- awk '/^[0-9]+$/' $1 | while read i
- do
- echo "$i is a number"
- done
-
- Regards, Alan
-
- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
- Maidenhead itself is too snobby to be pleasant. It is the haunt of the
- river swell and his overdressed female companion. It is the town of showy
- hotels, patronized chiefly by dudes and ballet girls.
-
- Three Men In A Boat, Jerome K. Jerome, 1889
- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-