Re: bash: how to split a $var ?
* David selby
> In bash how can I split a string eg ...
>
> var1=0624todaysfile
>
> I want var2 to equal the first 4 digits, ie 0624
> My first instinct was cut but this is for files only, head & tail are
> of no use ...
Cut can be used, and it is instructive to see how you use filters like
cut to get what you want. You have to use echo in order to get the
filter streaming correctly:
echo $var1 | cut -c1-4
However, as long as you know that bash is in use, you have substring
function in bash:
echo ${var1:0:4}
These two works when you know that the variable is excactly like that,
i.e. the first four characters are to be taken. But regular
expressions can also be picked out:
echo ${var1%t*}
If you need a reasonable portal solution, sed is a choice:
echo $var1 | sed 's/[^0-9].*//'
--
Jon Haugsand, Jon-H.Haugsand@norges-bank.no
http://www.norges-bank.no
Reply to: