Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

get digits

Status
Not open for further replies.

ogniemi

Technical User
Nov 7, 2003
1,041
PL
how to get only digits from a variable?

for example, variable can be set to one of the following:

42d43%
9845dhg984$sfd9%
sd@#948**##376

I need output:

4243
98459849
948376

thank you in advance.
 
Hi

Code:
var=`echo $var | tr -dc '[:digit:]'`

[gray]# or[/gray]

var=`echo $var | sed 's/[^[:digit:]]//g'`

[gray]# or[/gray]

var=`echo $var | awk '{gsub(/[^[:digit:]]/,"")}1'`

Feherke.
 
As this is an awk forum...

Code:
echo abc12 def34% 8dbc9|awk '{
 for (i=1;i<=NF;i++)
 {
  var="";
  for (j=1;j<=length($i);j++)
  {
   if (((k=substr($i,j,1)) >= "0") && (k <= "9"))
    var=var k
  }
  printf "%s ", var
 }
 printf "\n"
}'


HTH,

p5wizard
 
Hi

Yep, was too late when I observed that I wrote in the [tt]awk[/tt] forum.

But I still prefer the [tt]gsub()[/tt] way.
Code:
gsub(/[^[:digit:]]/,"",[green][i]var[/i][/green])

Feherke.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top