wkde
wkde

Reputation: 453

How to remove 0's from the second column

I have a file that looks like this :

k141_173024,001
k141_173071,002
k141_173527,021
k141_173652,034
k141_173724,041
...

How do I remove 0's from each line of the second field?
The desired result is :

k141_173024,1
k141_173071,2
k141_173527,21
k141_173652,34
k141_173724,41
...

What I've tied was

cut -f 2 -d ',' file |  awk '{print $1 + 0} > file2

cut -f 1 -d ',' file > file1

paste file1 file2 > final_file

This was an inefficient way to edit it.
Thank you.

Upvotes: 1

Views: 595

Answers (5)

codeforester
codeforester

Reputation: 42999

If the second field is a number, you can do this to remove the leading zeroes:

awk 'BEGIN{FS=OFS=","} {print $1 OFS int($2)}' file

As per @Inian's suggestion, this can be further simplified to:

awk -F, -v OFS=, '{$2=int($2)}1' file

Upvotes: 2

potong
potong

Reputation: 58371

This might work for you (GNU sed):

sed 's/,0\+/,/' file

This removes leading zeroes from the second column by replacing a comma followed by one or more zeroes by a comma.

P.S. I guess the OP did not mean to remove zeroes that are part of the number.

Upvotes: 1

James Brown
James Brown

Reputation: 37404

If it's only the zeros following the comma (,001 to ,1 but ,010 to ,10; it's not remove 0's from the second column but the example doesn't clearly show the requirement), you could replace the comma and zeros with another comma:

$ awk '{gsub(/,0+/,",")}1' file
k141_173024,1
k141_173071,2
k141_173527,21
k141_173652,34
k141_173724,41

Upvotes: 3

ganit44
ganit44

Reputation: 517

awk 'BEGIN{FS=OFS=","} {print $1 OFS $2+0}' Input.txt 

Force to Integer value by adding 0

Upvotes: 4

RavinderSingh13
RavinderSingh13

Reputation: 133458

Could you please try following.

awk 'BEGIN{FS=OFS=","} {gsub(/0/,"",$2)}1' Input_file

EDIT: To remove only leading zeros try following.

awk 'BEGIN{FS=OFS=","} {sub(/^0+/,"",$2)}1'  Input_file

Upvotes: 2

Related Questions