Reputation: 21
I want ot replace exactly 1 leading zero with @, if 2 or more leading Zeros found then discard it.
0123
00123
000123
123
Output:
@123
00123
000123
123
I have tried
sed 's/^0.\{1\}/@/' file
Note : Please conside above 4 records in each line of file.
Upvotes: 1
Views: 81
Reputation: 8811
Using Perl
$ cat lead_zero.txt
0123
00123
000123
123
0
$ perl -pe ' s/(^0)(?!0+.*)/@/ ' lead_zero.txt
@123
00123
000123
123
@
$
If it is in second column of a pipe delimited file, then use this.
$ cat lead_zero.txt2
a|0123|x
b|00123|y
c|000123|xx
d|00000123|yy
e|123|zz
f|0|qq
$ perl -pe ' s/(.*?\|)0(?!0+.*)/$1@/ ' lead_zero.txt2
a|@123|x
b|00123|y
c|000123|xx
d|00000123|yy
e|123|zz
f|@|qq
$
Upvotes: 0
Reputation: 204731
You should have included a single 0 on it's own line in your sample input as that's an edge case that could be missed:
$ cat file
0123
00123
000123
123
0
$ sed -E 's/^0([^0]|$)/@\1/' file
@123
00123
000123
123
@
The above will work with any sed that has a -E
option to use EREs, e.g. GNU sed and BSD/OSX sed.
Upvotes: 2
Reputation: 37464
One in awk:
$ awk '{sub(/^0/,(/^00/?0:"@"))}1' file
@123
00123
000123
123
Explained:
$ awk '{sub(/^0/,(/^00/?0:"@"))}1' file
| | | | |
| | | | otherwise with a @
| | | with a zero
| | if followed by a zero
| leading zero
replace
and if it is in the second |
delimited field, use:
$ awk 'BEGIN{FS=OFS="|"}{sub(/^0/,($2~/^00/?0:"@"),$2)}1' file
1|@123|1
2|00123|2
3|000123|3
4|123|4
Upvotes: 2
Reputation: 189948
Your regex looks for a zero, followed by any character. You want to check that it is not followed by a zero, but not replace the nonzero character.
You can capture and put back the character you want to keep:
sed 's/^0\([^0]\)/@\1/' file
Or you can take care to only replace the first character on lines which match this regex:
sed '/^0[^0]/s/^0/@/' file
As ever, specifying that something is repeated exactly once is pointless and redundant.
Upvotes: 1