Before the cat
do an echo
or printf
of the filename:
while read line; do printf '%s\n' "$line"; cat "$line"; done <locationfile.txt >finalfile
Or, more readable:
while read line; do
printf '%s\n' "$line"
cat "$line"
done <locationfile.txt >finalfile
Note that this requires all paths in locationfile.txt
to have no \
in them.
Although having \
in path names is highly unusual, it would be safer to do
while read -r line; do
printf '%s\n' "$line"
cat "$line"
done <locationfile.txt >finalfile
... which doesn't have the same restrictions.
Adding a check to make sure the file actually exist too, and outputting a warning if it doesn't:
while read -r line; do
if [[ -f "$line" ]]; then
printf '%s\n' "$line"
cat "$line"
else
printf 'Warning: "%s" does not exist\n' "$line" >&2
fi
done <locationfile.txt >finalfile
"Does not exist" here means "is at least not a regular file".
If you want the ""
there as well, as a sort of end-of-file-contents-marker, just put that out after cat
:
while read -r line; do
if [[ -f "$line" ]]; then
printf '%s\n' "$line"
cat "$line"
echo '""'
else
printf 'Warning: "%s" does not exist\n' "$line" >&2
fi
done <locationfile.txt >finalfile
And finally, give things self-documenting names:
while read -r file_path; do
if [[ -f "$file_path" ]]; then
printf '%s\n' "$file_path"
cat "$file_path"
echo '""'
else
printf 'Warning: "%s" does not exist\n' "$file_path" >&2
fi
done <file_paths.txt >files_concat_with_paths.txt