5

I have 3 input files all having the same number of lines. I have come up with a movie example to make the question look interesting.

file1.txt -- Essentially contains the actor names.

1234|jacknicholson|actor
5678|jacknicholson|director
4321|christianbale|actor

file2.txt -- Contains the movies of the actors.

1234|oneflewovercuckoosnest^asgoodasitgets
5678|theshining
4321|batmanbegins^darkknight

file3.txt -- Residence of the actors.

1234|california
5678|hollywoodstudios
4321|losangeles

I am splitting the first input file based on the condition that if names are equal, I need to apply some algorithm. The command is as below.

awk -F '|' 'NR>1 && $2 != prev {print ""} {prev=$2; print}' file1.txt

The above command will make my first file (file1.txt) as,

1234|jacknicholson|actor
5678|jacknicholson|director

4321|christianbale|actor

I need to introduce the space at the same position in the remaining 2 files too so that I can apply my algorithm.

One approach that comes to my mind is, store the position of spaces in the file1.txt in an array and then when I encounter that position in the remaining 2 files, introduce the spaces.

2 Answers 2

5

To introduce a blank line in a file at the same position as changes in actors in file1.txt, try:

$ awk -F '|' '{save=$0; getline<"file1.txt"} NR>1 && $2!=prev {print ""} {prev=$2; print save}' file2.txt
1234|oneflewovercuckoosnest^asgoodasitgets
5678|theshining

4321|batmanbegins^darkknight

The above works quite a bit like your code except that it is extended to read two files at the same time. It reads from file2.txt and saves the line in the variable save. If then reads from file.txt, and using the same logic as your code, determines if the actor changes and, if so, prints a line break. It then prints the line it received from file2.txt.

1
  • I will check this solution as soon as I get into the server. Thanks a lot for providing a solution :)
    – Ramesh
    Apr 1, 2014 at 1:35
2

Another awk solution:

$ awk 'FNR==NR{if(!NF){a[FNR]=1}next}a[FNR]{print"\n"$0;next}{print}' file1.txt file2.txt
1234|oneflewovercuckoosnest^asgoodasitgets
5678|theshining

4321|batmanbegins^darkknight
  • When reading file1.txt, we mark the line number in array a if line is blank.
  • When reading file2.txt, we get line number which is blank in array a and print a blank line before it. For other lines, we print it normally.
1
  • Thanks for another awk solution. It also worked as expected :)
    – Ramesh
    Apr 1, 2014 at 3:39

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .