Sci-Tech Sci-Tech - 1 year ago 74
Linux Question

Bash: opening file which name in listed inside another file

I have a file that contains a list of file names to be opened later.
After I load lines (file names) to variables, for a reason unknown to me I cannot open it as a file later.

Here is a simplified example of what i'm trying to do:

Main file's contents:


Bash commands:

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

Execution esult:

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

cat first_file.txt
contains "first_file.txt", but
cat $line

I obviously misunderstand something here, suggestions are welcomed!

As requested, here is
cat -v $main_file
's output:



The ^M characters are carriage returns (a.k.a. \r) and are often part of a Windows line ending. They don't show up when you echo them, but they are messing up your ability to open a file with the text having it at the end.

The best solution is to remove them from your "main file." You could use the dos2unix tool if you have it, or you could use GNU sed like sed -i -e 's/\s+$//g' $main_file to edit it in place and remove the extra white space (which includes ^M) from the end of each line.