1828214 Members
2541 Online
109975 Solutions
New Discussion

Awk Question

 
Michael Brennan
New Member

Awk Question

I have a large list of telcom point codes which I am trying to format with awk. A point code (telecom) looks like the following:

002-345-067

Each point code will have three sections, each three numbers in length. Does anyone know of a good way in awk to remove the leading zeros of each of the fields so that the above point code would look like the following:

2-345-67

However I would want:

000-000-000

to be returned as:

0-0-0




7 REPLIES 7
Gregory Fruth
Esteemed Contributor

Re: Awk Question

You can split the code into 3 parts, then use printf to
print it the way you want.

echo 002-345-067 | awk '{split($0, a, /-/); printf "%d-%d-%d\n", a[1], a[2], a[3]}'
2-345-67

echo 000-000-000 | awk '{split($0, a, /-/); printf "%d-%d-%d\n", a[1], a[2], a[3]}'
0-0-0



Leif Halvarsson_2
Honored Contributor

Re: Awk Question

Set the fild separator FS="-" and then
use the printf statement

printf "%d","s","s","%d","%d", $1 "-" $2 "-" $3
Michael Kelly_5
Valued Contributor

Re: Awk Question

You can do with sed like this.
cat | sed -e 's/[0]\{1,2\}\([0-9]\)/\1/g'

HTH,
Michael.
The nice thing about computers is that they do exactly what you tell them. The problem with computers is that they do EXACTLY what you tell them.
Hai Nguyen_1
Honored Contributor

Re: Awk Question

Try this sed command:

# sed -e 's/^/-/' -e 's/-0/-/g' -e 's/-0/-/g' -e 's/^-//' original_file > new_file

Hai
H.Merijn Brand (procura
Honored Contributor

Re: Awk Question

pc03:/tmp/xx 507 $ echo "001-000003-43253-22" | perl -pe's/(\d+)/$1+0/ge'
1-3-43253-22
pc03:/tmp/xx 508 $

or in your case, change all in file and replace file

# perl -pi -e's/(\d+)/$1+0/ge' infile

Enjoy, have FUN! H.Merijn
Enjoy, Have FUN! H.Merijn
Ronelle van Niekerk
Regular Advisor

Re: Awk Question

I like this one:

cat $file | awk '{FS="-"; printf("%d-%d-%d\n",$1,$2,$3)}' > $new_file

Nice and clean.
rm -r /it/managers
Jean-Luc Oudart
Honored Contributor

Re: Awk Question

use following script
$1 is your code

#!/bin/sh

typeset -i g1 g2 g3
echo $1 | tr "-" " " | read g1 g2 g3 && echo $g1"-"$g2"-"$g3

example : scriptname = filter
filter 002-345-067
2-345-67

filter 000-000-000
0-0-0
Rgds,
Jean-Luc
fiat lux