LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   BASH: string is "charset=iso-8859-1", I want to extract "iso-8859-1" only. How?? (https://www.linuxquestions.org/questions/programming-9/bash-string-is-charset%3Diso-8859-1-i-want-to-extract-iso-8859-1-only-how-4175429942/)

rm_-rf_windows 10-01-2012 03:25 PM

BASH: string is "charset=iso-8859-1", I want to extract "iso-8859-1" only. How??
 
Hello all,

I think this is an easy question to answer, but I can't seem to figure it out. 'sed' is for files, not variables...

I get:
Code:

<myfile>: text/x-c++; charset=iso-8859-1
as output, the result of
Code:

file -i <myfile>
I've stored this little result ("<myfile>: text/x-c++; charset=iso-8859-1") into a variable and would like to get yet another variable which contains the string "iso-8859-1" only (length may vary depending on the encoding), in other words, to extract the part of the string that follows "charset=" up until the end ot the string. It seems simple, but I just can't figure it out!

Thanks in advance,

rm

kaiserkarl13 10-01-2012 03:53 PM

This should work:
Code:

var1="<myfile>: text/x-c++; charset=iso-8859-1"
var2=$(echo $var1 | cut -f2 -c=)

Alternatively, you can use sed:
Code:

var1="<myfile>: text/x-c++; charset=iso-8859-1"
var2=$(echo $var1 | sed 's/^.*=//')


catkin 10-01-2012 04:20 PM

Alternatively
Code:

var1='<myfile>: text/x-c++; charset=iso-8859-1'
var2=${var1##*=}

That is shell parameter expansion. The ## means "strip the longest string matching what comes next from the left side". Shell parameter expansion is a powerful technique and runs faster than using awk, cut or sed (provided the strings are less than a few thousand characters). Unfortunately it's not very intuitive.

rm_-rf_windows 10-02-2012 06:11 AM

Many thanks to both or you. It worked like a charm!

I'm going to post my second question in a separate post (text format conversion, no longer above for those of you who didn't answer this post. It can be found here: http://www.linuxquestions.org/questi...95#post4794795).

rm


All times are GMT -5. The time now is 07:27 PM.