Skip to main content
2 of 3
added 36 characters in body
Peter.O
  • 33.8k
  • 32
  • 120
  • 167

If you want to concatenate a list of files. Youc can check each one as follows:

# some sample files
printf "%s\n" abc > file1  
printf "%s"   def > file2  # no trailing newline
printf "%s\n" abc > file3
printf "%s"   def > file4  # no trailing newline

tmp="$(mktemp)"; echo >$tmp  # a file which contains only a `\n`
cmd=cat
for file in file1 file2 file3 file4; do
    [[ $(tail -c1 $file | hexdump -ve '1/1 "%02x"') == 0a ]] && nl= || nl=" $tmp"
    cmd="$cmd \"$file\"$nl"
done
eval "$cmd"

The concatenated result is:

abc
def
abc
def

The generated command is:

cat "file1" "file2" /tmp/tmp.nEdFkdWgJe "file3" "file4" /tmp/tmp.nEdFkdWgJe
Peter.O
  • 33.8k
  • 32
  • 120
  • 167