Operating System - HP-UX
1752761 Members
5447 Online
108789 Solutions
New Discussion юеВ

sed -- last field replace

 
SOLVED
Go to solution

sed -- last field replace

sed last field replace

text file ...
hello"|"\388"|"376"|""
hello"|"\388"|"376"|"meANDyou"

sed file
s/|""$/Z/g

results ..
hello"|"meANDyou"|"\388"|"376"Z
hello"|"meANDyou"|"\388"|"376"|"meANDyou"

using sed how can I replace the "meANDyou" or any other quoted text or digits that is on the end of the line with a Z ?

Steve
5 REPLIES 5
Dennis Handly
Acclaimed Contributor
Solution

Re: sed -- last field replace

If you want to replace quoted text:
sed -e 's/|".*"$/Z/'

Did you want to replace quoted numbers or just raw numbers? For the latter:
sed -e 's/|[0-9]*$/Z/'

And you can combine both -e patterns.

Hmm, this doesn't work because it will replace your "\388" string too. So you may need to use awk -f"|" and replace field $4.

Or using this sed pattern assuming 4 fields with "|":
's/\(.*\)|\(.*\)|\(.*\)|".*"$/\1|\2|\3|Z/'

This takes the fields apart and only puts back the first 3.
Peter Godron
Honored Contributor

Re: sed -- last field replace

Steve,
#!/usr/bin/sh
cat a.lis
awk -F'|' '{
for (i=1;iprintf "%s|",$i
printf "Z"
printf "\n";
}' < a.lis

Produces:
hello"|"\388"|"376"|""
hello"|"\388"|"376"|"meANDyou"
hello"|"\388"|"376"|Z
hello"|"\388"|"376"|Z

First two lines are the original input, next two the output.

Please also read:
http://forums1.itrc.hp.com/service/forums/helptips.do?#33 on how to reward any useful answers given to your questions.

You currently have only awarded points to 1 of 23 answers.
Peter Nikitka
Honored Contributor

Re: sed -- last field replace

Hi,

it is not clear, if you want to have the additional string enclosed in double quotes or have the double quotes of the last field replaced.

txt='hello"|"\388"|"376"|"meANDyou"'
First (Leave quotes):
echo $txt |sed 's/[^"]*"$/Z"/'
hello"|"\388"|"376"|"Z"

Second (drop quotes):
echo $txt |sed 's/"[^"]*"$/Z/'
hello"|"\388"|"376"|Z

mfG Peter
The Universe is a pretty big place, it's bigger than anything anyone has ever dreamed of before. So if it's just us, seems like an awful waste of space, right? Jodie Foster in "Contact"

Re: sed -- last field replace

Peter Nikitka...

That works perfectly

Thank you,
Steve

Re: sed -- last field replace

Peter Nikitka

Hd the answer I was needing and the other had solutions too :)