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

标签 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

我尝试过许多不同的代码变体。有些只会返回项目而不是 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

(顺便说一下,您的问题是 sedread 都在从 itemlist.txt 中读取;read 获取第一行,sed 消耗其余部分。您的 while 循环在第一次迭代后退出。)

关于bash - 如何使用多个循环并将输出存储到多个变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36829361/

相关文章:

linux - 后台接地和子处理期间的可变可访问性

linux - PLINK 命令执行但未创建文件

linux - 为什么 "echo"没有出现在 "ps"中?

linux - Bash 找到字符并删除右侧的所有字符

MySQL加载数据: This command is not supported in the prepared statement protocol yet

regex - sed 命令在 solaris 中有效,但在 Linux 中无效

bash 变量在curl命令中

git - 启动 GitBash 时未执行 .bashrc

bash - 在 bash 命令行输出中转义空格

linux - 打印 file1 到 file2 的差异而不删除 file2 中的任何内容