简体   繁体   English

在bash中使用变量替换获取错误

[英]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" 这是文件“ 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 提前非常感谢您给我一个提示

You can't escape spaces like that and have the shell operate on the escaped filenames the way you are trying to. 您不能逃避这样的空间,而让shell以您尝试的方式对转义的文件名进行操作。 But you don't need to do that either. 但是您也不需要这样做。 This is what tools like xargs and such are for. 这就是xargs类的工具的用途。

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. 最好使用read和遍历文件的各行,然后逐行进行匹配,如果匹配则逐行匹配mv Though I imagine many other options are also available depending on what the data sources are exactly. 尽管我想象根据数据源的确切情况,还有许多其他选项可用。

The mv is expanding to something like: mv正在扩展为:

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". 因此,它将空格上的单词分开,然后尝试将“ ./P1/San”和“ A_P1”移动到“ SanAndrés”中。

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

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