如何改组包含空格的文件名数组? [英] How can I shuffle an array of filenames that have spaces in them?

查看:94
本文介绍了如何改组包含空格的文件名数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文件名数组,其中可能包含空格。我正在使用 shuf 命令,但它使用文件名中的空格作为分隔符,并在改组时拆分文件名。有没有办法解决这个问题,还是我必须放弃 shuf 命令?有什么建议吗?

I have an array of filenames that may contain spaces in them. I am using the shuf command but it uses the spaces in the filenames as a delimiter and breaks up the filenames when it shuffles. Is there a way around this or do I have to abandon the shuf command? Any suggestions?

#!/bin/bash

vids=()

vids+=("file with spaces.txt")

for arr in "${vids[@]}"; do
    echo -e "$arr\n"
done

vids=( $(shuf -e "${vids[@]}") )    #shuffle contents of array

for arr in "${vids[@]}"; do
    echo -e "$arr\n"
done

exit 0

输出:

file with spaces.txt

file

with

spaces.txt


推荐答案

您的方法不起作用的原因是,shell在 $(...),并且无法将换行符视为分隔符。您可以使用 mapfile 将行读入数组(在Bash 4+中):

The reason your approach doesn't work is that the shell applies word splitting to the output of a command inside $(...), and there's no way to treat newlines as a separator. You could either use mapfile to read lines into an array (in Bash 4+):

mapfile -t vids < <(shuf -e "${vids[@]}")

Bash您可以在循环的同时使用老式的

Or in older versions of Bash you could use good old-fashioned while loop:

vids2=()
while read -r item; do
    vids2+=("$item")
done < <(shuf -e "${vids[@]}")

这篇关于如何改组包含空格的文件名数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆