对字符串的迭代包含空格

时间:2014-11-05 09:26:05

标签: bash

我正在对远程文本文件内容进行简单的迭代,但因为内部有空格而无法拆分文件名。

#!/bin/bash
for u in $(curl http://XXXXXX.com/urls.txt)
do
    wget "${u%|*}" -O "${u#*|}" -P ./Directory/
done

文本文件每行包含以下字符串:

https://OOOOOOOO.com?url1|My file with spaces in name.mp4
https://OOOOOOOO.com?url2|How to escape spaces?.mp4
https://OOOOOOOO.com?url3|Mixed up.mp4
https://OOOOOOOO.com?url4|Asking StackOverFlow!.mp4

我已经看过许多类似的问题,做了很多方法,但结果都是一样的。

当我单独进行echo ${u#*|}时,我有输出:

My
file
with
spaces
in
name.mp4
Mixed
up.mp4
.
.
.

怎么了?

2 个答案:

答案 0 :(得分:2)

while-read循环在这里会更简单:

curl http://XXXXXX.com/urls.txt |
while IFS='|' read -r url filename; do
    wget "${url}" -O "${filename}" -P ./Directory/
done

答案 1 :(得分:1)

使用Input Field Separator (IFS)

  

此变量确定Bash如何识别字段或单词   边界,当它解释字符串时。   LINK

e.g:

IFS=$'\n'
for u in $(cat file)
do
   echo ${u#*|}
done

输出:

My file with spaces in name.mp4
How to escape spaces?.mp4
Mixed up.mp4
Asking StackOverFlow!.mp4