I know that both will copy data from f1.txt to f2.txt, but what is the real difference?
(cp f1.txt f2.txt)
(less f1.txt > f2.txt)
The difference is that
cp is far clearer to humans. That is one of the first things you should be optimizing for.
less in this way is so obscure, it's not really obvious that it works unless you try it out. The other answer points out that it doesn't work - if your file contains certain characters, and you expect the command to work without user interaction, e.g. as part of a script. This limitation is also obscure (at least I didn't think of it, despite having seen this behavior plenty of times).
less happens to be slower, one reason is it transfers data in smaller chunks. Run them under
strace, I see
less chunks 1023 bytes (1KiB - 1); cp chunks 64KiB.
less has been designed as a pager (e.g .with next page functionlity) for text files. As such it is less optimized for copying files than say
cp (which has been designed to copy data), and might have a considerable overhead, thus lacking in performance.
cp won't ask you for confirmation when handling files that contain special (e.g. control) characters.
cp example, you need to run exactly one program (
less example, the
less command actually only outputs the contents of the given file to
stdout and your shell redirects the stdout into a new file, so you are actually running two programs (one output, and one input).
cp variant is faster because it doesn't dump
f1.txt contents to the screen:
$ time cp f1.txt f2.txt real 0m0.002s user 0m0.004s sys 0m0.000s $ rm f2.txt $ time less f1.txt > f2.txt real 0m0.009s user 0m0.004s sys 0m0.000s
cp vs 0.009 for
cpcan save some mode bits of the original file while
lesscreates a new file with modes according to
(...) each destination file is created with the mode bits of the corresponding source file, minus the bits set in the umask and minus the set-user-ID and set-group-ID bits.
cpis shorter to type. Seriously, it matters when you spend most of your time in command line.
Going on a tangent here since you're asking about
*.txt files, there's one slight benefit of using
less, which is to use its pre-processing feature to "modify the way the contents of the file are displayed". A contrived example would be to output the contents of a compressed file to the output:
less compressed.txt.gz > uncompressed.txt
But of course, that can, and probably should, be better done by
zcat -c compressed.txt.gz > uncompressed.txt.
Still, I'm guessing this can be practical for environments where the
less pre-processing is standardized (check for the environment variable
LESSOPEN, which usually points to a file
/usr/bin/lesspipe.sh), so that scripts/commands do not need to be concerned with parsing the input file into the target file.
I've also found this link where it shows more uses cases. As mentioned above, check your Linux environment's
/usr/bin/lesspipe.sh to see what are the variety of files that
less can extract textual information from.