简体   繁体   English

使用sed查找/替换文件名

[英]find / replace on a file name using sed

I'm iterating over every file in a directory and attempting to find/replace the path part of the file with the following piece of code... 我正在遍历目录中的每个文件,并尝试使用以下代码查找/替换文件的路径部分...

for f in /the/path/to/the/files/*
do
    file = $(echo $f | sec 's/\/the\/path\/to\/the\/files\///g`);
done  

However, I get the following error with the assignment part of my code... 但是,我的代码分配部分出现以下错误...

cannot open `=' (No such file or directory)

What am I doing wrong? 我究竟做错了什么?

You must write = without spaces around it: 您必须编写=周围没有空格:

for f in /the/path/to/the/files/*
do
 file=$(echo $f | sec 's/\/the\/path\/to\/the\/files\///g');
done  

Also, it would be better to use another symbol, not /, as a sed delimiter: 另外,最好将另一个符号(而不是/)用作sed分隔符:

for f in /the/path/to/the/files/*
do
 file=$(echo $f | sec 's@/the/path/to/the/files/@@g')
done  

You cannot put spaces on either side of the equals sign: 您不能在等号的两侧放置空格:

for f in /the/path/to/the/files/*
do
    file=$(echo $f | sed 's/\/the\/path\/to\/the\/files\///g`);
done  

Parameter expansion is a better way to accomplish this, however: 参数扩展是实现此目的的更好方法,但是:

for f in /the/path/to/the/files/*
do
    file=${f#/the/path/to/the/files/}
done  

Try: 尝试:

for f in /the/path/to/the/files/*; do
    # no spaces around = sign
    file=$(echo $f | sed "s'/the/path/to/the/files/''g");
done

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

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