Issue
Solaris , VERSION: 11.10.0,REV=2005.01.21.15.53
I have a file test.txt
which contains values like below:
<Info>
<AccountNumber>23456789</AccountNumber>
<BranchNumber>004</BranchNumber>
<TransitNumber>01646</TransitNumber>
<NameAndCity>XYZ Bank</NameAndCity>
<OwnerFullName>ABC XYZ</OwnerFullName>
</Info>
All the info is in a line and we have multiple lines like above also other tags are available.
It contains other tag values as well. Also if the tag values contains "333" combination, I don't want to replace them.
I want to use sed command to replace value of the tag with 33333 and after replacement, I want to save the updated info to same file.
Output should be :
<Info>
<AccountNumber>33333333</AccountNumber>
<BranchNumber>33333</BranchNumber>
<TransitNumber>3333333</TransitNumber>
<NameAndCity>333 33333</NameAndCity>
<OwnerFullName>3333 33333</OwnerFullName>
</Info>
I am new to shell script and not exactly able to write the pattern to match it.
Here is what i have implemented so far to first two tag values but it is not working:
sed 's/(<AccountNumber>)\+[0-2,4-9]*$/\1 33333333/' test.txt
sed 's/(<BranchNumber>)\+[0-2,4-9]*$/\1 33333/' test.txt
Any help will be appreciated .
Solution
Try this:
sed -e '/333/!{' -e 's#<AccountNumber>[0-9]*</AccountNumber>#<AccountNumber>333333333</AccountNumber>#;s#<BranchNumber>[0-9]*</BranchNumber>#<BranchNumber>33333</BranchNumber>#;}'
Eg:
$ sed -e '/333/!{' -e 's#<AccountNumber>[0-9]*</AccountNumber>#<AccountNumber>333333333</AccountNumber>#;s#<BranchNumber>[0-9]*</BranchNumber>#<BranchNumber>33333</BranchNumber>#;}' test.txt
<Info>
<AccountNumber>333333333</AccountNumber>
<BranchNumber>33333</BranchNumber>
<TransitNumber>01646</TransitNumber>
<NameAndCity>XYZ Bank</NameAndCity>
<OwnerFullName>ABC XYZ</OwnerFullName>
</Info>
A very straightforward way, if you test ok and want to change the file inplace, add -i
switch.
I don't have Solaris to test, so can't be sure.
Try this simple perl
one see if it's working:
perl -pe 's#<AccountNumber>[0-9]*</AccountNumber>#<AccountNumber>333333333</AccountNumber>#' test.txt
If it's working, we can add others.
So for your logic first wrote in the question, it should be like this:
perl -pe 'unless (/333/) {s#<AccountNumber>[0-9]*</AccountNumber>#<AccountNumber>333333333</AccountNumber>#;s#<BranchNumber>[0-9]*</BranchNumber>#<BranchNumber>33333</BranchNumber>#;}' test.txt
You can add other substitudes yourself. the #
is to replace the usual /
of s
, an easier way to avoid escape the /
in close tags (I.E. s#from#to#;
).
It's rather straightforward so I think you'll have no difficulty :)
Add -i
switch to change inplace, like this: perl -i -pe '...
.
Answered By - Tiw