How to insert at a particular position in flat file

Hi All,
I have a flat file with ~ as de-limiter (e.g: aaa~ba a~caa~0~d~e)
What I want is check if the 4th character is 0 and replace it with say 4. So now it becomes : aaa~ba a~caa~4~d~e.

I have to do this for the whole file, but the delimiter position remains the same, not the character length.

Please help.
Abhi.

Try this..

awk -F"~" '{if ($4==0) $4=4; print $0;}' filename

To start:

pattern=$1
rep_string=$2
awk -F\~ -v pat=${pattern} -v rep=${rep_string} 'BEGIN{OFS=FS}{if ( $4 == pat){sub(/'"${pattern}"'/,rep,$4)}print}' txt

cat filename | cut -d "~" -f 4|sed -e 's/0/4/'

awk -F'~' 'BEGIN{OFS="~";}{ if ($4 != 4){$4=4;} print }' your_file

As per the req it should have been like

awk -F'~' 'BEGIN{OFS="~";}{ if ($4 == 0){$4=4;} print }' your_file

Hi Jacoden

I tried it , but i have lost my de-limiters '~' and got only space instead.

Abhi.

Thanks a lot this works.

Abhi.

Yes..I missed to include the O/p Field seperator.

Correct code is

awk -F"~" '{OFS="~"; if ($4==0) $4=4; print $0;}' filename

Thanks Jacoden, its working now !!

A possible 'sed' version:

sed 's:~:@|:3;{s:@|0~:~4~:;s:@|:~:;}' input_file
awk 'BEGIN{OFS=FS="~"}$4==0{$4=4;print}'