user1357015
user1357015

Reputation: 11676

rename file names work in command prompt but not in bash script

I'm trying to rename commands in a bash script. If I run for example:

echo /home/scientist/mySalesData/campaignData_1482386214.24417.csv  | sed 's/\(.*\)\(_.*\)/mv \"&" \"\1.csv\"/' | bash   

It works fine and gives me campaignData.csv in the directory /home/scientist/mySalesData/ .

However, if I put this in a bash script as follows:

for f in /home/scientist/SalesData/*; do
if [ -f "$f" ]; 
  cp "$f" /home/scientist/SalesForce/SalesData/Backups/                                                                
  echo $f$ | sed 's/\(.*\)\(_.*\)/mv \"&" \"\1.csv\"/' | bash |        
fi 
done 

I get:

mv: cannot stat '/home/scientist/SalesData/campaignData_1482386214.24417.csv$': No such file or directory          

Any help would be much appreciated!

Upvotes: 0

Views: 44

Answers (2)

Roland Illig
Roland Illig

Reputation: 41617

cd "$srcdir"
for f in *; do
  if [ -f "$f" ]; then
    cp "./$f" "$dstdir/${f%_*}.csv"
  fi
done

The % is the strip shortest suffix pattern operator.

Upvotes: 2

heemayl
heemayl

Reputation: 41987

You have a trailing $ here:

echo $f$

remove that (and quote the expansion):

echo "$f"

You could use here string too:

sed ... <<<"$f"

Upvotes: 2

Related Questions