Reputation: 41
Say I have a data file with rows like a^I^I^I^I^I^I^Ib^Ic
, which is separated by ^I
(means a tab).
Now, I want to change the empty value of each column into 0, so the result should be like: a^I0^I0^I0^I0^I0^I0^Ib^Ic
.
How can I achieve it with only one sed command?
Upvotes: 0
Views: 2415
Reputation: 15461
With GNU sed:
sed ':a;s/\t\(\t\|$\)/\t0\1/;ta' file
Replace all \t
followed by \t
or end of line with \t0
.
Upvotes: 1
Reputation: 203645
$ awk '{while(gsub(/\t\t/,"\t0\t"));} 1' file
a 0 0 0 0 0 0 b c
Upvotes: 0
Reputation: 67507
another awk
$ awk -v RS='\t' -v ORS='\t' '$0==""{$0=0}1'
or with BEGIN block
$ awk 'BEGIN{RS=ORS="\t"} $0==""{$0=0}1'
Upvotes: 0
Reputation: 74625
This is easier to do using a tool with support for look-ahead:
perl -pe 's/\t(?=\t)/\t0/g' file
This puts a "0" in between any pair of tab characters. The look-ahead is useful as it matches the second tab without consuming it, so it can be used in the next match.
Here's a way you could do it using awk:
awk -F'\t' -v OFS='\t' '{ for (i = 1; i <= NF; ++i) sub(/^$/, 0, $i) } 1' file
This loops through all the fields, substituting all empty ones with a 0.
Upvotes: 1