2

I need to replace last dot to character '-' in the string.

# a='2.5.2.pl'

Using the following expression:

# echo ${a/%./-}

I expect to get:

2.5.2-pl

but i get

2.5.2.pl

I noticed that it doesn't work only if I need to replace the dot from the end to the beginning. Why does it happen? Of course I can use external programs like awk, sed to solve this problem but I need to solve the problem using only bash.

Thanks for advice!

0

2 Answers 2

6

With bash‘s Parameter Expansion:

a='2.5.2.pl'
echo "${a%.*}-${a##*.}"

Output:

2.5.2-pl
Sign up to request clarification or add additional context in comments.

Comments

0

My way is a bit hacky and uses rev but I tested it and it works!

echo "$(_b=$(echo "$a" | rev); _b=${_b/./-}; echo "$_b" | rev)"

Basically, I just reversed the character order so the last . was first and then used ${var/./-} to replace the dot with a dash and finally reversed the order of the characters again.

5 Comments

There's quite a set of bugs here. Try having whitespace-surrounded wildcards, tab characters, or other oddness in your strings -- and see BashPitfalls #14. (The ease of having something look like it works, while having bugs when executed with even slightly-different data, is part of why it's important to understand the execution model for bash, rather than accepting a successful test to have meaning besides the specific inputs and domain where that test took place).
I don't see that being a problem with what the OP asked.
Code gets reused outside its initial domain. Robust practices are safely reusable; fragile practices... aren't. And reuse isn't always intentional, either -- the worst data loss event I was present for happened when someone was sloppy in quoting in a shell script because it "could only ever" run in a directory containing names matching [0-9a-f]{24} -- then a bug in a separate program created a filename with garbage dumped from memory, and the script expanded a glob in that name and deleted TB of billing data backups.
Anyhow, part of the point of StackOverflow is that we're creating a teaching resource -- it's a reasonable expectation that code given in a teaching resource is going to be correct, not full of hidden pitfalls and caveats.
Okay, I'll update it to something that should work outside of it's initial domain.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.