Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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.

share|improve this question

2 Answers 2

up vote 3 down vote accepted

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.

share|improve this answer
    
I will check this solution as soon as I get into the server. Thanks a lot for providing a solution :) –  Ramesh Apr 1 at 1:35

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.
share|improve this answer
    
Thanks for another awk solution. It also worked as expected :) –  Ramesh Apr 1 at 3:39

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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