You could also accomplish this with avconv based on
avconv -i <sourcefile> -c:v libx264 -crf 23 output.mp4
you can adjust the quality upwards by reducing the crf factor (23 in the example) and adjust downwards by increasing it.
You can set the values between 0 and 51, where lower values would result in better quality (at the expense of higher file sizes). Sane values are between 18 and 28. The default for x264 is 23, so you can use this as a starting point.
A script that should allow you to change to a different format with no loss of quality (but little or no reduction in size would be
echo "This script will attempt to copy the video and audio streams of all non-mkv files in the current directory to a mkv video container of the same name as the sources without overwriting."
read -p "Press any key to continue or CTRL-C to cancel"
for f in *.*
name=$(echo "$f" | sed 's/\.[^\.]*$//')
ext=$(echo "$f" | sed 's/^.*\.//')
echo "$f is made up of the base $name and ends with $ext"
echo target = $target
if [ "$f" = "$target" ];
echo "$f=$target skipping overwrite"
avconv -i "$f" -c:a copy -c:v copy "$name.mkv"
Note that the audio and video codecs in use in this script are
copy so no re-encoding should take place. Any savings in size will be minimal and will only be the result of a more efficient container than previously in use. To obtain a reduction in size, re-encoding is required and you'd need to adjust the script by replacing
c:v copy with
-c:v libx264 -crf 23 (adjusting the -crf value to your needs as mentioned above). Feel free to comment out or remove any superfluous echo lines.
Note: The formats you mention "mp4, flv, m4v, mpg, mov, avi" are containers and have little or no bearing on the codecs used to encode the streams within them. A discussion regarding re-encoding for size reduction would require knowledge of the codecs contained in the containers and would have to be evaluated on a case by case basis.
Sources: Testing and http://slhck.info/articles/crf