Bash shell script -- split string INCLUDING the delimeter?
I'm wondering if there's a simple way to split a string into an array and INCLUDE the delimeter?
For example:
foo = "a;b;c;d;"
Would parse to:
"a;" "b;" "c;" "d;"
It seems most functions strip out the delimeter.
Edit: I need to end up not with echoed ou开发者_StackOverflow社区tput but an array that I can then manipulate later in the script. Also, it's probably easiest if the string can be read from a text file.
foo="a;b;c;d;"
for z in $(echo $foo | sed -r 's/([^;]+;)/\1 /g')
do
echo $z
done
a;
b;
c;
d;
(After edit) How to make an array:
# declare -a arr
arr=($(echo $foo | sed -r 's/([^;]+;)/\1 /g'))
Note: As Glenn pointed out, it will fail, if blanks build part of the content.
My handbook says, that I should use declare -a
to declare an array, but in praxis it seems, I don't need it.
declare -a Array=($(echo 'a;b;c;' |cut -d';' --output-delimiter="; " -f1-))
echo ${Array[2]}
> c;
declare -a Array=($(echo 'a;b;c' |cut -d';' --output-delimiter="; " -f1-))
echo ${Array[2]}
> c
That's pretty gross, but hey, it kind of works. You'll need a different delimiter if you have spaces in your input, so this is not ideal.
foo='foo bar;abc def;ghi;jlk;'
oldIFS="$IFS"
IFS=\;
declare -a ary=($foo)
for ((i=0; i<${#ary[@]}; i++)); do ary[$i]="${ary[$i]}$IFS"; done
IFS="$oldIFS"
echo "${ary[1]}" # ==> "abd def;"
Ruby(1.9+)
$ array=( $(echo "a;b;c;d;" | ruby -e 'gets.chomp.scan(/(\w;)/).each{|x|print "%s " % x}') )
$ echo ${array[0]}
a;
$ echo ${array[1]}
b;
$ echo ${array[2]}
c;
$ echo ${array[3]}
d;
You may change the IFS value inside a function so that the IFS value outside that function remains unchanged.
And you can append a string to every array element without looping as well.
(
printf '%q\n' "$IFS"
splitButKeepDelim() {
declare IFS="$1" # limit scope of IFS
array=( ${2} ) # hardcoded array name
IFS=""
array=( "${array[@]/%/;}" ) # append a ';' to every array item
return 0
}
unset array
splitButKeepDelim ';' 'a;b;c;d;'
printf '%s\n' "${array[@]}"
printf '%q\n' "$IFS"
)
精彩评论