简体   繁体   English

用 sed 替换字符串的一部分

[英]Replace a part of a string with sed

I have a with location:我有一个位置:

/Users/spotter/Downloads

and within the Downloads folder there are two files:在下载文件夹中有两个文件:

test1.txt and test2.txt . test1.txttest2.txt

I want to write a shell script to save all the files to a list with a line like this:我想编写一个 shell 脚本来将所有文件保存到一个列表中,如下所示:

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

and echo $file_list will return: echo $file_list将返回:

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

However I want to change part of the dirname.但是我想更改目录名的一部分。 Particularly I want to change the /Users/spotter part to gs://my_bucket特别是我想将/Users/spotter部分更改为gs://my_bucket

I tried this like so:我这样试过:

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

which returns:返回:

sed: no input files

when I do echo $file_list I want this to be the output:当我做echo $file_list我希望这是输出:

gs://my_bucket/Downloads/test1.txt

gs://my_bucket/Downloads/test2.txt

EDIT:编辑:

I MUST use ls and I need to keep the entire string replacement within the single list at the end somehow or another.我必须使用ls并且我需要以某种方式将整个字符串替换保留在最后的单个列表中。

With GNU find:使用 GNU 查找:

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

or only with bash:或仅使用 bash:

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

如果您可以从 ls 移动到 find 并希望坚持使用 sed:

file_list=$(find /Users/spotter/Downloads -type f | sed 's|/Users/spotter/|gs://my_bucket/|g')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM