我正在尝试使用名为 itemlist.txt
的文本文件,其中包含:
http://example.com/item-a
http://example.com/item-b
http://example.com/item-c
http://example.com/item-d
http://example.com/item-e
我尝试过许多不同的代码变体。有些只会返回项目而不是 url。我不知道如何正确分配 $url
。这是我最接近实现所需输出的结果。
#!/bin/bash
while read url; do
for item in $(sed "s/http:\/\/example.com\///g"); do
echo $item $url; done
done < itemlist.txt
期望的输出是:
item-a http://example.com/item-a
item-b http://example.com/item-b
item-c http://example.com/item-c
item-d http://example.com/item-d
item-e http://example.com/item-e
但我得到的是:
item-b http://example.com/item-a
item-c http://example.com/item-a
item-d http://example.com/item-a
item-e http://example.com/item-a
有人可以阐明如何正确执行此操作吗?
最佳答案
不要使用sed
;只需使用参数扩展来删除 URL 中直到并包括最后一个 /
的所有内容。
while IFS= read -r url; do
item=${url##*/}
echo "$item $url"
done < itemlist.txt
(顺便说一下,您的问题是 sed
和 read
都在从 itemlist.txt
中读取;read
获取第一行,sed
消耗其余部分。您的 while
循环在第一次迭代后退出。)
关于bash - 如何使用多个循环并将输出存储到多个变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36829361/