简体   繁体   English

拆分包含 '&&' 的 Bash 字符串

[英]Split Bash String That Contain '&&'

I have a bash script like this:我有一个像这样的 bash 脚本:

#!/bin/bash

params="path=/me & you/folder/file.json&&user=Bob"
splitParams=(${params//&&/ })

for i in "${!splitParams[@]}"
do
    echo "$i: ${splitParams[i]}"
done

It produces:它产生:

0: path=/me
1: &
2: you/folder/file.json
3: user=Bob

But when I type em in shell:但是当我在 shell 中输入 em 时:

➜  params="path=/me & you/folder/file.json&&user=Bob"
➜  splitParams=(${params//&&/ })
➜  echo $splitParams
path=/me & you/folder/file.json user=Bob

I expect the output from script is like when I typed in shell:我希望脚本的输出就像我在 shell 中输入时一样:

0: path=/me & you/folder/file.json
1: user=Bob

echo $splitParams only prints the first element. echo $splitParams只打印第一个元素。 Use declare -p to see exactly what's in the array:使用declare -p来准确查看数组中的内容:

$ declare -p splitParams
declare -a splitParams=([0]="path=/me" [1]="&" [2]="you/folder/file.json" [3]="user=Bob")

So now how can you split the string at && but not have whitespace mess things up?那么现在如何在&&处拆分字符串,但又不让空格弄乱呢? Well, relying on the shell to do it is error-prone.好吧,依靠shell来做是容易出错的。 Changing && into spaces and splitting on spaces runs into trouble when the input string already contains spaces.当输入字符串已包含空格时,将&&更改为空格并在空格上拆分会遇到麻烦。

A better way to do it is to change the delimiters into newlines.更好的方法是将分隔符更改为换行符。 Then instead of using array=($string) to break $string apart, use readarray so spaces don't trigger splitting, only newlines.然后,不要使用array=($string)$string分开, readarray使用readarray以便空格不会触发拆分,只会触发换行符。

$ readarray -t splitParams < <(sed 's/&&/\n/g' <<< "$params")
$ declare -p splitParams
declare -a splitParams=([0]="path=/me & you/folder/file.json" [1]="user=Bob")
grep -oP '(?<=^|&&).*?(?=&&|$)' <<< "path=/me & you/folder/file.json&&user=Bob"

prints:印刷:

path=/me & you/folder/file.json
user=Bob

You may use something like this:你可以使用这样的东西:

params="path=/me & you/folder/file.json&&user=Bob"
while IFS=  read -r -d $'\0'
do
  splitParams+=("$REPLY")
done < <(echo "${params}" | awk -F'&&' '{ for (i=1;i<=NF;i++) printf("%s\0",$i); }')

for i in "${!splitParams[@]}"
do
    echo "$i: ${splitParams[i]}"
done

Output:输出:

0: path=/me & you/folder/file.json
1: user=Bob

You can use awk for that purpose, but remember that splitParams can not be accessible outside of the awk.您可以为此目的使用 awk,但请记住,在 awk 之外无法访问 splitParams。 We will use awk's split function:我们将使用 awk 的 split 函数:

split([String to be proccessed], [Array for results], [Delimeter]) split([要处理的字符串], [结果数组], [Delimeter])

#!/bin/bash
params="path=/me & you/folder/file.json && user=Bob"
awk -F: '{split($0, splitParams, "&&"); print splitParams[1] "\n"splitParams[2]}' <<< $params

Output:输出:

 path=/me & you/folder/file.json
  user=Bob

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM