简体   繁体   English

将字符串拆分为数组(以“\\”分隔)

[英]Split string into array (delimited by “\ ”)

I'm currently writing a bash script.我目前正在编写一个 bash 脚本。 Let's assume I have the following string:假设我有以下字符串:

C:\Program Files\Folder1\ C:\Program Files\Folder2\ C:\Program Files\Folder3\ 

This string can contain an unknown amount of windows locations.此字符串可以包含未知数量的窗口位置。 Now I need to split the string into an array at the end of each location, so each location has its own key in the array.现在我需要在每个位置的末尾将字符串拆分为一个数组,因此每个位置在数组中都有自己的键。 The main problem are the spaces in every path (Program Files).主要问题是每个路径(程序文件)中的空格。

What I've tried so far:到目前为止我尝试过的:

Using IFS variable:使用 IFS 变量:

oldIFS="$IFS"
IFS="\ "
myArray=( $myString )
IFS="$oldIFS"

The Problem here is, that it cuts the locations on every backslash, not just backslash and whitespace as it was intended.这里的问题是,它削减了每个反斜杠上的位置,而不仅仅是预期的反斜杠和空格。 So C: is the first element of my array.所以C:是我数组的第一个元素。

Using read command:使用读取命令:

IFS="\ " read -ra myArray "$myString"

Same problem as before.和以前一样的问题。

Any ideas on how to solve this?关于如何解决这个问题的任何想法?

Edit: I'm not using real bash but git bash on windows.编辑:我不是在使用真正的 bash,而是在 Windows 上使用 git bash。 So not every bash command is available.所以并不是每个 bash 命令都可用。

You can use this script:你可以使用这个脚本:

s='C:\Program Files\Folder1\ C:\Program Files\Folder2\ C:\Program Files\Folder3\'
IFS='^K' read -ra arr < <(sed 's/\\ /^K/g' <<< "$s")

OR Non-BASH或非 BASH

echo "$s" | sed 's/\\ /^K/g' | IFS='^K' read -ra arr

Testing:测试:

declare -p arr
declare -a arr='([0]="C:\\Program Files\\Folder1" [1]="C:\\Program Files\\Folder2" [2]="C:\\Program Files\\Folder3\\")'

PS: Here ^K is actually Control V K PS:这里^K其实是Control V K


You can also use awk :您还可以使用awk

echo "$s" | awk -F '\\\\( |$)' '{for (i=1; i<=NF; i++) if ($i) print $i}'
C:\Program Files\Folder1
C:\Program Files\Folder2
C:\Program Files\Folder3

For array creation:对于数组创建:

IFS=';' arr=($(echo "$s" | awk -F '\\\\( |$)' -v ORS=';' '{for (i=1; i<=NF; i++) 
     if ($i) print $i}'))

Probably no filename contains a tab, and the following will work:可能没有文件名包含选项卡,以下将起作用:

IFS=$'\t' read -ra the_files <<<"${the_string//\\ /$'\\\t'}"

In the unlikely case that a filename does contain a tab, you could change the tab character above to something else, like \\1 .在不太可能的情况下,文件名确实包含制表符,您可以将上面的制表符更改为其他内容,例如\\1

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

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