0

If my variable has data as,

test="score=5,grade=d,pass=f,"

Anyway I can extract the data/rewrite the data from/into the variable as,

test="score,grade,pass"

I do not need the data between =, &, and , characters.

1
  • I do not need the data between "=" and "," Commented Jul 28, 2015 at 10:26

2 Answers 2

5

In pure bash (no external tools like sed or awk or perl required), you can use "Parameter Expansion" to manipulate strings. You can read about this in Bash's man page.

#!/usr/bin/env bash

test="score=5,grade=d,pass=f,"

# Use the "extglob" shell option for "extended" notation on patterns.
shopt -s extglob

# First, remove the bits from equals to before each comma...
test="${test//=+([^,]),/,}"

# Next, remove the trailing comma.
test="${test%,}"

echo "$test"

And here's a demo.

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

3 Comments

Wow, that works! As I am very new to unix, could you please explain how it works? Would help me frame my own statements for any similar issues in future
@Noobie, I added comments to this to help explain the various steps. If the patterns are what you need help with, the best place to start is the "Parameter Expansion" section of the Bash man page. You can search that page for "extglob" as well, for a detailed description of how this works and what the options are.
I'm very glad I could help. :-) If this solved your problem, please feel free to click the checkmark beside my answer, to mark this question as answered!
0

You may use sed.

echo "score=5,grade=d,pass=f," | sed 's/=[^,]*\(,$\|\)//g'

or

echo "score=5,grade=d,pass=f," | sed 's/=[^,]*\|,$//g'

DEMO

6 Comments

I am not able to get the same results in my terminal, It just displays the entire string back to me. Any reason why it could be happening?
Sorry, but the new one gave me the same results
I am running it in bash
I see that this works in GNU sed, but neither of these works in FreeBSD or OSX. You could use the sed script 's/=[^,]*,/,/g;s/,$//' instead. This has pretty much nothing to do with bash.
@User112638726, per re_format(7) or regex(7) (depending on your OS), the vertical bar is a regular character in BRE. The fact that its ERE functionality can be found in some RE parsers is non-standard and not universal. One option would be to use ERE instead of BRE, i.e. sed -E 's/=[^,]*|,$//g' (or -r for GNU sed and some other implementations). Of course, implementations vary. Use what works. :)
|

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.