11

I have tried to get the 2 files output in a single file. I have tried below command:

cat file1 file2

but here file2 data is appending to file1.

What I need is file1 1st line followed by file2 first line, and file1 second line followed by file2 second line etc.

Can anybody tell me how to do this in a simple way?

4 Answers 4

20

There's an app for that!

$ cat file1
file1 line1
file1 line2

$ cat file2
file2 line1
file2 line2

Now, if you pass these files as arguments to paste:

$ paste -d' ' file1 file2
file1 line1 file2 line1
file1 line2 file2 line2

If by "file1 1st line followed by file2 first line, and file1 second line followed by file2 second line etc.", you mean that you want a new line between each line pasted, simply adjust the -d (delimiter) option.

$ paste -d'\n' file1 file2
file1 line1
file2 line1
file1 line2
file2 line2
0
2

POSIX Awk; this works with an arbitrary amount of files, and the files don’t even have to have the same amount of lines. The script keeps going until all files are out of lines:

BEGIN {
  do {
    br = ch = 0
    while (++ch < ARGC)
      if (getline < ARGV[ch]) {
        printf ch < ARGC - 1 ? $0 FS : $0 RS
        br = 1
      }
  } while (br)
}
1
  • There's one problem with it, if input contains '%' characters it tried to eval them inside printf. My update would be (I'm not sure this is perfectly correct): printf "%s", ((ch < ARGC - 1) ? $0 FS : $0 RS) Jan 7, 2017 at 21:38
0

Quick bash solution

# Takes as many file arguments as needed
function InterleaveFiles {

    local counter=0
    local hasLine=true

    while [ $hasLine == true ]; do
            hasLine=false
            for i in "$@"; do
                    line=$(awk 'NR == num_line {print; exit}' num_line=$((counter+1)) "$i")
                    if [ -n "$line" ]; then
                            echo "$line"
                    hasLine=true
                    fi
            done
            counter=$((counter+1))
    done
}

InterleaveFiles file1 file2 file3 file4

-2
paste -d '\n' file1 file2 > file3

where file1 and file2 are the input files and file3 will be the created output.

1
  • 1
    Welcome to the U&L Stack Exchange! This answer is almost identical to terdon's answer. In cases where you think you can improve on an answer, but don't provide substantially new information, please considering proposing an edit to an existing answer. Answers are also reordered based on voting, so each answer should stand on its own or refer to other answer. That's why shell oneliners should be accompanied by a description that explain their operation. Sep 25, 2014 at 11:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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