sumit gupta sumit gupta - 5 months ago 16
Linux Question

insert symbol between numbers

I have a file in Linux OS containing some random numbers:

1
22
333
4444
55555
666666
7777777
88888888


Now, I have two conditions:
1. Remove last 3 digit from every entry and put
/
in between rest.
2. For the numbers <=3, just add/replace with
/
symbol.

command I am trying which fulfilling only 1st requirement is:

sed -e 's|\(.\)|\1/|g;s|\(.*\)/\(.\/\)\{3\}|\1|g'


Desired out required:

/
/
/
4
5/5
6/6/6
7/7/7/7
8/8/8/8/8


Please help.

Answer

Something like this might work for you:

% sed 's/.\{1,3\}$//;s/./\/&/g;s/.//;s/^$/\//' file
/
/
/
4
5/5
6/6/6
7/7/7/7
8/8/8/8/8

No smart moves here:

s/.\{1,3\}$//; # Remove last 3 character
s/./\/&/g;     # Insert / before each character
s/.//;         # Remove first character (it's now a /)
s/^$/\//       # Insert slash on all empty lines

Alternative solution with gawk:

awk -v FS='' -v OFS='/' '{if (NF > 3) NF=(NF-3); else $0 = OFS}1' file