用 sed 替换字符串的一部分

斯特凡诺·波特

我有一个位置:

/Users/spotter/Downloads

在下载文件夹中有两个文件:

test1.txttest2.txt

我想编写一个 shell 脚本来将所有文件保存到一个列表中,如下所示:

file_list="$(ls /Users/spotter/Downloads)"

并且echo $file_list将返回:

/Users/spotter/Downloads/test1.txt /Users/spotter/Downloads/test2.txt

但是我想更改目录名的一部分。特别是我想将/Users/spotter部分更改gs://my_bucket

我这样试过:

file_list="$(ls /Users/spotter/Downloads | while read path; do dirname "$path" | sed -i "s|/Users/spotter|gs://my_bucket|g"; done)"

返回:

sed: no input files

当我这样做时,echo $file_list我希望这是输出:

gs://my_bucket/Downloads/test1.txt

gs://my_bucket/Downloads/test2.txt

编辑:

我必须使用ls并且我需要以某种方式将整个字符串替换保留在最后的单个列表中。

居鲁士

使用 GNU 查找:

file_list=$(find /Users/spotter/Downloads/ -type f -printf 'gs://my_bucket/Downloads/%f\n')

或仅使用 bash:

cd /Users/spotter/Downloads/
file_list=$(for i in *.txt; do echo "gs://my_bucket/Downloads/$i"; done)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章