-2

I have file1:

1
5
4

and file 2:

44
65
56

I want to file.out:

1
44
5
65
4
56

Thank you

RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
Lukáš Altman
  • 497
  • 1
  • 5
  • 15

3 Answers3

4

use paste with custom delimiter \n i.e line feed:

paste -d '\n' file1 file2 > file.out

or GNU sed:

sed 'R file2' file1

or awk:

awk 'NR==FNR{a[NR]=$0;next} {print a[FNR]} 1' file1 file2
oguz ismail
  • 1
  • 16
  • 47
  • 69
3

paste is the better way, but with awk you can use getline to read from another file while reading some file:

awk -v f2="file2" '{print; getline < f2; print;}' file1
muru
  • 4,723
  • 1
  • 34
  • 78
1

Could you please try following solution, it will work for more than 2 Input_file(s) in case you have too.

awk 'FNR==NR{a[FNR]=$0;next} {a[FNR]=(a[FNR]?a[FNR] ORS:"")$0} END{for(i=1;i<=FNR;i++){print a[i]}}'  Input_file1  Input_file2


EDIT: Adding 1 more generic solution, where we could pass N number of files to it moreover it is NOT assuming that number of lines in all Input_file(s) are same, it gets the maximum number of lines from all the files and will print matching lines(with line number in all files) and will print lines(which are more in number in any file at last too), in case OP's files have this condition.

Let's say we have 3 files named file1, file2 and file3 as follows.

cat Input_file1
1
5
4

cat Input_file2
44
65
56

cat Input_file3
1
2
3
4
5
6

Now following is the code.

awk '
prev!=FILENAME{
   count=count>prev_count?count:prev_count
}
{
   prev_count=FNR
}
FNR==1{
   prev=FILENAME
}
FNR==NR{
   a[FNR]=$0
   next
}
{
   a[FNR]=(a[FNR]?a[FNR] ORS:"")$0
}
END{
   count=count>prev_count?count:prev_count
   for(i=1;i<=count;i++){
      print a[i]
   }
}'   Input_file1  Input_file2   Input_file3

Output will be as follows.

1
44
1
5
65
2
4
56
3
4
5
6
RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93