Split string into 2, from 2nd occurance of a character in bash
I have a script, which is having a string as command line argument.
1= "ABC_MY_STING_anything_I_dont_care" I need to have 2 variables var1 = "ABC_MY" var2 = "STRING_anything_I_dont_care" Seperation is based on the "2nd" occurance of underscore. I found answers on how to do it in python but I'm using bash. Using tr doesnt look to solve this. I tried using IFS=_ but that splits my string in a way I dont want, I need only 2 parts. I know how to make regex but not getting how to split it this way. anything_something_rest_of_the_things [a-z A-Z 0-9]_[a-z A-Z 0-9]_ Background: Currently I use mutt -s $1 to send email But I need to split my email into 2 parts, var1 I'll use as subject and var2 I'll use as message body. |
maybe something like
Code:
s1=`echo $1 | cut -d _ -f -2` |
Quote:
Quote:
|
Quote:
d tells that delimiter is _ and what about f |
Now that I have my subject in the s1 and body in s2. I cant find out a way to make s2 as the body. I wish to use mutt but, it expects file for making its body. Can anyone help on this.
|
Sorry, never used Linux, so someone might need to help edit this.
As far as regex-matching the text-strings, here's a sed example: GNU version 4.0.7 sed -r -n 's/([^_]*_[^_]*)_(.*)/AnyTextHere \1/p' $1 sed -r -n 's/([^_]*_[^_]*)_(.*)/AnyTextHere \2/p' $1 They only output below vars if $1 meets your 2nd-occurrence requirement. \1 = AllTextBefore2ndOccurenceOf_ \2 = AllTextAfterwards You can always combine the \1\2 replacements, editing AnyTextHere with your needed apps (separated by &&) and then pipe to 'sed e' to auto-run the replacement text-string as a commandline. |
IF $1 is of format: Mail_Subject_Body Text
Try something like below, but remove ;e for testing Again, someone may need to help edit this for a bash shell sed -r 's#([^_]*_[^_]*)_(.+)#echo -e "\2" | mutt -s "\1" user@earth.com#;e' $1 It creates text-lines as: echo -e "Body Text" | mutt -s "Mail_Subject" user@earth.com If that's not what you need, mod the replacement & test again. Once in the correct format, add ;e back-in to execute the result. ** Edit ** Removed sed's -n and s///p option to make it simpler. Its fine so long as $1 will always be in the right format If not, give e a linematch like /@/e (for lines with email or whatever) Or just pipe the changed $1's only with something like: sed -n -r 's#([^_]*_[^_]*)_(.+)#echo -e "\2" | mutt -s "\1" user@earth.com#p' $1 | sed e |
See the manual for cut
http://unixhelp.ed.ac.uk/CGI/man-cgi?cut Delimiter is _ (underscores) in your case. -f is the field list (as found using the delimiter you specified). -f1-2 means fields 1 to 2. -f3- means from field no 3 onwards. OK |
echo $s2 | mutt $s1 should be OK. If not, then substitute mutt with mailx.
OK |
that looks overkill and overcomplicated for me. we can use IFS:
Code:
string="ABC_MY_STING_anything_I_dont_care" |
All times are GMT -5. The time now is 02:57 AM. |