ashok viswanathan
ashok viswanathan

Reputation: 117

Truncate Leading Zeroes and Padding Equal Number of Spaces to particular fields in UNIX

How to remove leading zeroes from particular columns and padding with equal number of spaces.

A001|XYZ|00001|00234|0090
B001|XYZ|00010|00234|0990
C001|XYZ|00321|00234|0345
D001|XYZ|05001|00234|0777

Fields 3 and 5 are integer fields and output should be as below-

A001|XYZ|1....|00234|90..
B001|XYZ|10...|00234|990.
C001|XYZ|321..|00234|345.
D001|XYZ|5001.|00234|7...

('.' represent spaces)

Upvotes: 1

Views: 272

Answers (2)

NeronLeVelu
NeronLeVelu

Reputation: 10039

sed ':again
   s/^\(\([^|]*\|\)\{2\}\)0\([0-9]*\)/\1\3 /
   t again
   s/^\(\([^|]*\|\)\{4\}\)0\([0-9]*\)/\1\3 /
   t again' YourFile

easier for any columns (if needed)

sed ':again
   s/\|0\([0-9]*\)/\1 /g
   t again' YourFile

Upvotes: 0

jaypal singh
jaypal singh

Reputation: 77085

Very trivial using awk and printf:

awk '
BEGIN { FS = OFS = "|" }
{   len = length ($3)
     $3 = sprintf ("%*-d", len, $3)
    len = length ($5)
     $5 = sprintf ("%*-d", len, $5)
}1' file
A001|XYZ|1    |00234|90
B001|XYZ|10   |00234|990
C001|XYZ|321  |00234|345
D001|XYZ|5001 |00234|777

Identify the length of the field. Using sprintf assign the value to the same column. Using * allows us to capture the number of spaces required from the length of the field taken from argument.

Upvotes: 2

Related Questions