0

I have a variable name in Bash as:

var=(any_word)_SuSE_11_design_guides

I want to manipulate the name such that I can have:

x=$(echo "$var" | some operation)
echo $x
SuSE_11_design_guides

Basically I want to remove every character behind first _ when detected. How to achieve this?

1
  • what you're saying makes NO sense, if you are "removing" everything behind first _ then echo $x would have whatever's (any_word) and NOT SuSE_11_design_guides. Because if you wanted that then you'd simply set x=SuSE_11_design_guides and you're done. Instead do you mean that you trying to get (any_word) in x? Commented Feb 4, 2017 at 4:45

3 Answers 3

1

I think you meant retain Everything behind first _ , which can be achieved using parameter-expansion.

string="(anyword)_SuSE_11_design_guides"
printf "%s\n" "${string#*_}"
SuSE_11_design_guides
Sign up to request clarification or add additional context in comments.

Comments

1

It's unclear whether you want to print SuSE_11_design_guides, or whatever came before. So, I'll answer both.

# Print the content before the first `_`
echo $var | awk -F_ '{ print $1 }'

If you want to print the trailing part:

echo $var | sed -E 's/.*(SuSE_11_design_guides).*/\1/'

Comments

0
$ var=(any_word)_SuSE_11_design_guides
$ echo ${var##${var%%SuSE_11_design_guides}}
SuSE_11_design_guides

The above echo statement is comprised of two nested bash strings function. Breaking down what this does, it is the equivalent of:

let a=${var%%SuSE_11_design_guides}

The above line strips "SuSE_11_design_guides" off the tail of $var returning the prefix

${var##$a}

The above strips whatever is in $a (which happens to be the prefix as per the previous step), from the beginning of $var, leaving the suffix.

I combined them in the original example just because I could. It definitely makes it harder to read, but I was going for shock value :-)

Comments

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.