As the title says.
I am creating a new thread on this subject because I cannot find BK's original.
(# Edit, an hour later: please see below, MochiMoppei found it.)
Barry asked an interesting question, because we often need to fish out some info
in the middle of a main string, and it seems there is no straightforward way to do it
in Bash.
I did provide a tentative solution at the time, based on the delimiter in Barry's
example, which was a double-colon, IIRC.
(# Edit, an hour later: Some other developers did as well.)
The following is NOT based on a delimiter, but please see the concluding note in
the example below.
Feedback welcome.
BFN
~~~~~~~~~~~~~~~~~~~~~
Code: Select all
###############
-- Trying to mimic "Intersection" in Boolean logic --
(Please pardon my French, "Intersection" may have another name in English.
I mean the C part when circles A and B overlap.)
x=2 ########################## How many char. we want (approx.) out of the
Z="ba;be;bi;bo;bu;by" ######## middle of this string. (Acts as an "accordeon".)
############################## Note 1) : x should not be 1.
############################## Note 2) : not considering delimiters. The
############################## string could as well be "Fish and potatoes",
############################## which has the same length.
a="${#Z}" #################### We fetch the length of the string.
echo $a
b="`echo "($a/$x)-1" | bc`" ## Will give us the length of the string divided
############################## by the number of characters that we want minus
echo $b ###################### one because position one of the string in human
############################## terms is position zero as bash understands it.
c="`echo "$a-($x*$b)" | bc`" # This is the actual number of characters that
echo $c ###################### we will get from the middle of the string.
echo "${Z:$b:$c}" ############ If x=1 above, we get the last character
# b="`expr $b + $c`" ######### Same intersection starting from the end of the
# echo "${Z: -$b:$c}" ######## string, with the new $b to compensate for the
############################## backwards calculation.
Results:
17
7 (char. 8 in human terms)
3 (size of sub-string)
i;b (the contents in the middle of the sting)
############################## About delimiters: to provide a more general
############################## solution, this script should contain a "delimiter
############################## detector". This was the idea in my 1st example;
############################## is the delimiter "b" or ";"?
############################## (With a view of confusing the script and the
############################## script writer!)
#
############################## Once we have this "delimiter selector" (ideally),
############################## the script could use awk or cut.