如何使用多个循环并将输出存储到多个变量?

I0_*_*_ol 3 bash

我正在尝试使用名为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
Run Code Online (Sandbox Code Playgroud)

我尝试了很多不同的代码变体.有些人只返回项目,但不返回网址.我无法弄清楚如何$url正确分配.这是我最接近实现所需输出的方法.

#!/bin/bash

while read url; do 
for item in $(sed "s/http:\/\/example.com\///g"); do
echo $item $url; done
done < itemlist.txt
Run Code Online (Sandbox Code Playgroud)

所需的输出是:

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
Run Code Online (Sandbox Code Playgroud)

但相反,我得到:

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
Run Code Online (Sandbox Code Playgroud)

有人可以说明如何正确地做到这一点?

che*_*ner 7

不要用sed; 只需使用参数扩展即可删除/URL中的最终内容.

while IFS= read -r url; do
    item=${url##*/}
    echo "$item $url"
done < itemlist.txt
Run Code Online (Sandbox Code Playgroud)

(你的问题,顺便说一下,就是这两个sedread来自阅读itemlist.txt,read获取第一线,和sed消耗休息你.while在第一次迭代后退出循环.)