This question already has an answer here:

I want to write an script which has as arguments two files F1 and F2 and prints them alternatively; first will be written F1's first line, then F2'2 second line and so on. If one of them has less lines than the other, when we finish to print the shorter one, the script should write the longest until the end.

My idea was:

1) Check if there are not 2 arguments -> echo and exit 2) Check if F1 or F2 aren't files -> echo and exit 3) Body:

exec 3 < $1
exec 4 < $2
while read -u 3 line && ((i==0))
echo line; echo
    while read -u 4 line && ((j==0))
        echo line; echo
 exit $?

Doubt: This would only work if both files have the same number of lines. How can I improve this to extend this solution to files with different size?

marked as duplicate by don_crissti, Wildcard, Jeff Schaller, HalosGhost, GAD3R Nov 5 '16 at 19:13

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.


No need for a shell script. You can do this directly with paste, which is specified by POSIX:

paste -d '\n' file1 file2

However, it doesn't handle different line counts the way you are describing. To quote the specs:

If an end-of-file condition is detected on one or more input files, but not all input files, paste shall behave as though empty lines were read from the files on which end-of-file was detected....

I personally think it would be a mistake to make the behavior as you describe in your question. You would be unable to tell, looking at line 24 of the output, whether it came from file1 or file2. With the actual behavior of paste, you would know it came from file2, since it's an even line number of the output.

You can pipe the output through tr -s '\n' like so:

paste -d '\n' file1 file2 | tr -s '\n'

But, if there are actual blank lines in either file, you will not get the expected results.

  • Thank you Wildcard for your help I aprreciate it, because it was what I need. It was just an excercise to learn bash scripting, and even more I learnt about the paste utility which I have used for the first time. Also to accomplish the script to find if all script's arguments where files I learnt to use "$@". – enoy Nov 6 '16 at 11:10
  • @enoy, glad to hear it. Don't forget you can "accept" the answer by clicking the checkmark to the left of the answer. (That's the preferred way to communicate "thanks, it worked" on this site.) :) – Wildcard Nov 6 '16 at 18:48

Not the answer you're looking for? Browse other questions tagged or ask your own question.