Another.Chemist
Another.Chemist

Reputation: 2559

Getting error with variable replacement in bash

Good day people,

I am wondering why I am getting this error:

$ DEPARTAMENTO="San Andrés" ; mv `grep "${DEPARTAMENTO:0:5}" ARCHIVOS2MOVER |  sed 's/ /\\ /g'` "$DEPARTAMENTO" ; echo "$DEPARTAMENTO"
mv: cannot stat `./P1/San': No such file or directory
mv: cannot stat `A_P1': No such file or directory
mv: cannot stat `./P2/San': No such file or directory
mv: cannot stat `A_P2': No such file or directory
San Andrés

This is a part of the file "ARCHIVOS2MOVER"

./Norte de Santander/Norte_P2
./P1/San A_P1
./P1/Total_P1
./P2/San A_P2
./P2/Total_P2
./Putumayo/Putum_P1

Thanks so much in advance for dropping me a clue

Upvotes: 1

Views: 58

Answers (2)

Etan Reisner
Etan Reisner

Reputation: 80921

You can't escape spaces like that and have the shell operate on the escaped filenames the way you are trying to. But you don't need to do that either. This is what tools like xargs and such are for.

Try something like:

grep "${DEPARTAMENTO:0:5}" ARCHIVOS2MOVER | xargs -d '\n' mv -t "$DEPARTAMENTO"

Not that I think this is the best way to do this either but it will work given the data as given.

It might be better to loop over the lines of the file with read and and do the match line-by-line and mv each one if they match. Though I imagine many other options are also available depending on what the data sources are exactly.

Upvotes: 6

Douglas
Douglas

Reputation: 37763

The mv is expanding to something like:

mv ./P1/San A_P1 "San Andrés"

So it is splitting the words on the space, then trying to move "./P1/San" and "A_P1" into "San Andrés".

Upvotes: -2

Related Questions