Bera
Bera

Reputation: 1282

using sed to remove only the last pattern matched on string

I'm trying to accomplish the following result

Given a bash script executed with the following parameter

#Input
./xxx.sh "\\\"P1\\\"\\\"P2\\\"\\\"P3\\\"\\\"P4\\\"\\\"P5\\\""

I want to remove the fifth parameter

#Output
# "\\\"P1\\\"\\\"P2\\\"\\\"P3\\\"\\\"P4\\\""

Doesn't matter with the fifth parameter is empty \\\"\\\" or not \\\"P5\\\"

I did the script bellow but it only remove if the last parameter is empty. And if I need to remove the forth an third parameters too, for example, how can I proceed?

a=$*

b=` echo $a | sed 's/[\\"[:alnum:]\\"]*$//g' ` 
b=` echo $a | sed 's/[\\"*\\"]*$//g' `
#the last try bellow give me the reasonable result when the fifth param is empty
b=` echo $a | sed 's/[\\"\\"]*$//g' ` 
echo $b

Sorry, I'm so far to be a shell guy

I got problems in ksh shell, but this works

b=` echo $a | sed -e 's/\\\\"[^"]*\\\\"$//g' `

Thanks guys

Upvotes: 1

Views: 80

Answers (2)

perreal
perreal

Reputation: 98118

Using sed:

b=`sed 's/\\\\"[^"]*\\\\"$//g' <<< "$a"`

Upvotes: 1

anubhava
anubhava

Reputation: 786091

Easier to do it using awk:

a="\\\"P1\\\"\\\"P2\\\"\\\"P3\\\"\\\"P4\\\"\\\"P5\\\""
awk 'BEGIN{FS=OFS="\\\\\\\""} {$10="";NF-=2}1' <<< "$a"
\\\"P1\\\"\\\"P2\\\"\\\"P3\\\"\\\"P4\\\"

Upvotes: 2

Related Questions