0

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
i=0
j=1
while read -u 3 line && ((i==0))
do
echo line; echo
 ((i++))
((j--))
    while read -u 4 line && ((j==0))
    do
        echo line; echo
 ((j++))
((i--))
   done
 done
 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?

Yone
  • 219

1 Answers1

2

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.

Wildcard
  • 36,499
  • 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 "$@". – Yone Nov 06 '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 06 '16 at 18:48