linux - Bash:打开另一个文件中列出的名称的文件

标签 linux bash

我有一个文件,其中包含稍后要打开的文件名列表。 在我将行(文件名)加载到变量后,由于我不知道的原因,我以后无法将其作为文件打开。

这是我正在尝试做的一个简化示例:

主文件内容:

first_file.txt
second_file.txt

bash 命令:

read line < $main_file   # file with the list, received as an argument
echo $line               # to check that correct filename has been read
cat $line                # attempt to dump "first_file.txt" contents <- FAILS
cat first_file.txt       # read "first_file.txt" contents manually 

执行结果:

first_file.txt
: No such file or directory
*** this is 1st file's contents ***
*** ....

因此,cat first_file.txt 有效,$line 包含“first_file.txt”,但 cat $line 失败...

我显然在这里误解了一些东西,欢迎提出建议!

编辑: 根据要求,这是 cat -v $main_file 的输出:

first_file.txt^M
second_file.txt^M
third_file.txt^M
^M
^M

最佳答案

^M 字符是回车符(又名 \r),通常是 Windows 行结尾的一部分。当您 echo 它们时,它们不会出现,但它们会扰乱您打开文件的能力,该文件的文本位于末尾。

最好的解决方案是将它们从“主文件”中删除。如果你有 dos2unix 工具,你可以使用它,或者你可以使用 GNU sed 像 sed -i -e 's/\s+$//g' $main_file 来就地编辑它并从每行的末尾删除多余的空格(包括 ^M)。

关于linux - Bash:打开另一个文件中列出的名称的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37378671/

相关文章:

Linux 庆典 : timeout a program if the program hangs in there and echo 'timeout'

bash - for循环检查多个var以返回空var的名称

linux - 从文本文件中获取值并在 UNIX 环境中进行计算

linux - nedit 命令别名导致功能中断

linux - omn​​ibus 或 source - 无法决定使用哪一个进行 gitllab 备份/恢复

python - session 未创建异常 : Message: session not created from disconnected: unable to connect to renderer using Chromedriver on Linux Centos 7 Server

c++ - 跟踪嵌入式实时 MPI 可执行文件中的内存使用情况

linux - 如何编写 git 命令来分离历史文件?

linux - 如何解析 bash 输出中的链接

Rmarkdown 无法正确重现 bash 代码