1

I have the following code:

testval="aaa_bbb_ccc," 
testval+="_ddd"
echo ${testval}

But, I need to get rid of the comma after "ccc". It will always be the last character of ${testval} before I add the "_ddd". There could be other commas that need to remain in the string.

But so far I can't find anything that works.

e.g.

testval="aaa_bbb_ccc," ; 
testval=${testval} | rev | cut -c 2- | rev ; testval+="_ddd" ; 
echo ${testval}

or

testval="aaa_bbb_ccc," ; 
testval=${testval} | sed 's/.$//' ; testval+="_ddd" ; 
echo ${testval}

both result in:

aaa_bbb_ccc,_ddd

I also tried:

testval="aaa_bbb_ccc," ; 
testval=$(${testval} | rev | cut -c 2- | rev) ; 
testval+="_ddd" ; 
echo ${testval}`

and

testval="aaa_bbb_ccc," ; 
testval=$(${testval} | sed 's/.$//') ; 
testval+="_ddd" ; 
echo ${testval}

both result in:

-su: {testval}: command not found**

Is there not the equivalent or rtrim of some similar function? that simply trims the last n characters from a string/variable

0

4 Answers 4

11

Is there not the equivalent or rtrim of some similar function? that simply trims the last n characters from a string/variable

Yes there is:

   ${parameter%word}
   ${parameter%%word}
          Remove matching suffix pattern.

The % form removes the shortest match while the %% removes the longest match. The corresponding "ltrim"s are ${parameter#word} and ${parameter##word}.

So for example

$ testval="aaa_bbb_ccc,"
$ testval=${testval%,}
$ echo ${testval}
aaa_bbb_ccc

For your case

$ testval="aaa_bbb_ccc,"
$ testval=${testval%,}
$ testval+="_ddd"
$ echo ${testval}
aaa_bbb_ccc_ddd

You can change , to ? to remove any single character; or use ??? to replace n=3 trailing characters and so on. In bash, word can be a KSH-style extended glob pattern if the extglob shell option is set.

0
5

There's only one comma in your initial string, so you'd be better off doing it in one replace operation than deleting the last character and then adding _ddd. e.g.

$ testval="aaa_bbb_ccc," 
$ testval="${testval/%,/_ddd}"
$ echo $testval
aaa_bbb_ccc_ddd

Because the pattern begins with a % bash attempts to match a comma, but only if it is at the end of the string. Compare the difference between this (and note the , i've used to replace the _ after aaa from your original string):

$ testval="aaa,bbb_ccc,"
$ testval="${testval/%,/_ddd}"
$ echo $testval
aaa,bbb_ccc_ddd

and this, without the %:

$ testval="aaa_,bbb_ccc,"
$ testval="${testval/,/_ddd}"
$ echo $testval
aaa__dddbbb_ccc,
0

You had the answer right there in your question. All you had to do was to add echo before ${testval}`

testval="aaa_bbb_ccc," ; testval=$(echo ${testval} | sed 's/.$//') ; testval+="_ddd" ; echo ${testval}
aaa_bbb_ccc_ddd
0

You can use awk:

testval="aaa_bbb_ccc,"
testval=$(echo $testval| awk '{sub(/.$/,"",$0);print $0"_ddd"}')

Resulting output:

aaa_bbb_ccc_ddd
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .