need help with replacing a certain field...

Hi, can anyone help me? This is what i want to do....I have a string

UNB+UNOA:1+OOCLIES+RTTC+080408:0358+1'

and i want to replace the "1" at the end (that specific field only) to 00001 such that the new output will be like this

UNB+UNOA:1+OOCLIES+RTTC+080408:0358+00001'

i tried using sed but it replaces all the "1"'s it encounters..i only need the "1" in the last part....maybe it has something to do with cut -d+ -f6? I'm not entirely sure...

I already figured out how to pad 1 with zeros to make it's width 5 but am having trouble with the replacement part.

Please help anyone...and thank you very much in advance!!!

One quick way using awk:

echo 'UNB+UNOA:1+OOCLIES+RTTC+080408:0358+1' | awk '{sub(/1$/,"00001")}1'

Output:

UNB+UNOA:1+OOCLIES+RTTC+080408:0358+00001

sed only the last digit.

 echo 'UNB+UNOA:1+OOCLIES+RTTC+080408:0358+1' | sed 's/[0-9]$/0000&/'
# echo "UNB+UNOA:1+OOCLIES+RTTC+080408:0358+1" | awk -F"+" '{$NF="00001"}1' OFS="+"
UNB+UNOA:1+OOCLIES+RTTC+080408:0358+00001

Hi all, thank you very much for your replies...but can you please explain what happened? Because i can see that you coded it as only "1", but see, these can be any number from 1-99999. what happens is i need to pad the said number with zeros to make it have a width of 5.

My code is as follows:

currCtlNo=`echo "UNB+UNOA:1+OOCLIES+RTTC+080408:0358+1" | cut -d+ -f6 | cut -d"'" -f1`
newCtlNo=$currCtlNo

typeset -Z5 newCtlNo

then i want to replace the last portion with the $newCtlNo..only the last portion

i already got it =)

UNB_seg="UNB+UNOA:1+OOCLIES+RTTC+080408:0358+1'"
currCtlNo=`echo $UNB_seg | cut -d+ -f6 | cut -d"'" -f1`
newCtlNo=$currCtlNo

typeset -Z5 newCtlNo

echo $UNB_seg | awk -F"+" '{$NF="'$newCtlNo'"}1' OFS="+" > newfile.txt
cat newfile.txt

the result is:
UNB+UNOA:1+OOCLIES+RTTC+080408:0358+00001'

but can you please explain the awk statement? :slight_smile: I would just like to better understand what happened. :slight_smile:

Thank you in advance!

and thank you everyone! :slight_smile: