Martin Cracauer via plug on 26 Apr 2023 13:50:20 -0700


[Date Prev] [Date Next] [Thread Prev] [Thread Next] [Date Index] [Thread Index]

Re: [PLUG] Splitting strings in bash


Walt Mankowski via plug wrote on Wed, Apr 26, 2023 at 03:46:08PM -0400: 
> Hi all,
> 
> I've got a question about splitting strings in a bash shell
> script. Let's say I've got a string
> 
> STR='dog cat'
> 
> I'd like to split that on the space into two variables, foo and bar. I
> tried this
> 
> echo $STR | read foo bar
> 
> but it doesn't work. On the following line foo and bar are back to
> their original values. Then, after looking through the bash manpage
> for an alternative, I tried this instead
> 
> read foo bar <<< $STR

That is a bash-ism, not Posix shell.

If you don't need the commandline args anymore, or good way to split a
variable portably is

set -- $STR
one=$1
two=$2
...

You can also use shift to iterate through the parts.


If you want to split for one-by-one processing you use
for var in $STR ; do echo $VAR ; done


You can also use single-use word splitting:
one=${STR% *}
two=${STR#* }
 
-- 
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Martin Cracauer <cracauer@cons.org>   http://www.cons.org/cracauer/
___________________________________________________________________________
Philadelphia Linux Users Group         --        http://www.phillylinux.org
Announcements - http://lists.phillylinux.org/mailman/listinfo/plug-announce
General Discussion  --   http://lists.phillylinux.org/mailman/listinfo/plug