0

Consider below variable letters="1234, MR45, MB46, 1234" Need a command to detect last occurrence of M[B or R] where M is fixed and second letter can be B or R and delete everything before it Expected output output="MB46, 1234" Also need if command to print error if letters variable doesnot have MB or MR word

0

Bash solution (regex matching):

letters="1234, MR45, MB46, 1234"

if [[ "$letters" =~ .*(M[BR].*) ]]; then 
    echo "${BASH_REMATCH[1]}"   # MB46, 1234
else 
    echo "MB or MR word not found!"
fi

As a simplified shortened alternative the following GNU grep approach may be used:

grep -Po '.*\KM[BR].*' <<<"$letters" || echo "MB or MR word not found"
  • thanks a lot it works fine...in the command sed 's/.*(M[BR].*)/\1/' how to detect the last ocuurence of the word MB or MR from variable even if the letters are in lower case – user8554534 Oct 15 '17 at 18:50
  • there's no sed solution now. I've updated my solution to fit your additional condition to print error if letters variable doesnot have MB or MR word. If you need case-insensitive search - you should mention that in your question – RomanPerekhrest Oct 15 '17 at 19:05
  • A bash/sed solution: sed -E 's/.*M([BR])/M\1/1' <<<"$letters" maybe? (add an if to it). – Arrow Oct 15 '17 at 22:52
  • Using if [[ "$letters" =~ .*(M[BR].*) ]]; then echo "${BASH_REMATCH[1]}" seems better IMvhO. – Arrow Oct 15 '17 at 22:56
  • @Arrow, as for .*(M[BR].*) - good hint, I've missed that. Thanks – RomanPerekhrest Oct 16 '17 at 6:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.