Replacing nulls using sed

Hi,

I am trying to replace nulls with spaces in every record of a '|' delimited file. I used this command -

cat input.dat | sed 's/||/| |/g' > output

But if a space appears twice '| | |' , then only the first null is getting replaced with a space. The second one remains as a null. I guess, this may be because I am not specifying the delimiter and checking for nulls. Can anyone help me out in this. Thanks a lot..!!!

sed 's/||/| |/g;s/||/| |/g' input.dat > output

I read that answer with interest. It does answer the OP's question.

But just on a side issue, why do we have to do this twice? Is it because the way sed works is that it will not reoperate on something it has just worked on in the same command?

i.e.

for the line:
|||

the command

sed 's/||/| |/g' 

works by doing
| ||

and because the second | has been operated on, sed will not evaluate it, and therefore the new line containing || is not picked up. Is this right?

thanks

Yes something like that. Once the pattern is treated, sed will stream further and look for the next mathing pattern.

Thanks Vino for that answer.

But, having to do it twice will replace two consecutive nulls. This means that we have to repeat this operation as many times as the maximum number of consecutive nulls appearing in the row.

Is there a way to make it replace nulls by giving it the delimiter '|' and asking it to replace null values?

Again, thanks for your time.

I dont quite get what you are saying. But running that sed statement once will replace all null's with a whitespace. All you need is 's/||/| |/g;s/||/| |/g'.

I think awk can do it.

Hi Vino,

I was mistaken. Sorry about that. This works.....

Thanks a lot..!!!

Hi,

If you are not sure how many || will appear continously, why not using loop?

Below is a sample, hope can help you more.

read a
echo $a | grep ||
num=`echo $?`
while [ $num -le 0 ]
do
	a=`echo $a | sed '/||/| |/'`
	echo $a | grep || 1>/dev/null
	num=`echo $?`
done
echo $a