sample.txt 文件包含以下值
1111
2222
3333
使用上述值将是访问名称为 1111
、2222
、3333
的文件夹的框架
我使用以下代码引用这些值
for i in $(cat sample.txt); do cd folder1/$i; done
它给出错误,因为 can't cd : folder1/1111
原因是因为从文件中引用的每个字符串值都有一些足够的空格或换行符..不确定
我尝试了以下命令但没有成功
for i in $(cat sample.txt); do i = $(echo ${i::-1 }); cd folder1/$i; done
for i in $(cat sample.txt); do i = $(echo $i | tr -d "[:space:]"); cd folder1/$i; done
for i in $(cat sample.txt); do cd folder1/$i; done
最佳答案
我猜你没有得到第一行的错误,但只从第二行开始。
如果你成功了
cd folder1/1111
命令
cd folder1/2222
将会失败,因为您已经在 folder1/1111
中。
您应该cd
返回到原始目录或执行cd
以及您想要在子shell 中执行的任何其他操作。
顺便说一句:你不应该阅读带有 for
的行,因为如果你有包含空格的行,这将失败。
参见 https://mywiki.wooledge.org/DontReadLinesWithFor
和 https://mywiki.wooledge.org/BashFAQ/001 .
这应该可行
while read -r dir
do
( cd "folder1/$dir" ) # ( ... ) to use a subshell
# after leaving the subshell, here we are back in the original directory
done < sample.txt
关于linux - 删除从文本文件中获取的字符串值的空格或换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55748824/