Skizit
Skizit

Reputation: 44842

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?

Upvotes: 0

Views: 813

Answers (3)

Ashish Kumar
Ashish Kumar

Reputation: 851

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

Upvotes: 0

chepner
chepner

Reputation: 531085

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  

Upvotes: 1

Igor Chubin
Igor Chubin

Reputation: 64563

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:

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

Upvotes: 3

Related Questions