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 two different files as shown below.

Content of a.txt:

HDR|1||||||||||               
DTL|@|||||||||||             
TLR|||||||||||||              
HDR|1||||||||||||            
DTL|||||||||||||              
TLR|||||||||||||     

Content of b.txt:

HDR|2||||||||||  
DTL|||||||||||||
TLR|||||||||||||
HDR|2|||||||||||| 
DTL|last||||||||||||
TLR|||||||||||||

Here I have to take out all the lines till 1st "TLR" in a.txt and b.txt and merge into 1.txt ,same way take out all the lines After 1st "TLR" in a.txt and b.txt and merge into 2.txt

output should be:

Content of 1.txt:

HDR|1|||||||||| 
DTL|@||||||||||| 
TLR|||||||||||||
HDR|2|||||||||| 
DTL|||||||||||| 
TLR|||||||||||||  

Content of 2.txt:

HDR|1|||||||||| 
DTL|||||||||||| 
TLR|||||||||||||
HDR|2|||||||||| 
DTL|last||||||||||| 
TLR|||||||||||||  

How can we accomplish this using UNIX Script?

share|improve this question
add comment

2 Answers 2

One way to do it:

sed -ne '1,/^TLR/p' a.txt > 1.txt
sed -ne '1,/^TLR/p' b.txt >> 1.txt
sed -e '1,/^TLR/d' a.txt > 2.txt
sed -e '1,/^TLR/d' b.txt >> 2.txt

That is:

  • Print the lines from a.txt until matching /^TLR/ and create 1.txt
  • Print the lines from b.txt until matching /^TLR/ and append to 1.txt
  • Drop the lines from a.txt until matching /^TLR/ and create 2.txt
  • Drop the lines from b.txt until matching /^TLR/ and append to 2.txt
share|improve this answer
add comment

You could run the same command twice on the two different files:

$ perl -ne 'print if $a<1; $a++ if /TLR/; ' a.txt > 1.txt
$ perl -ne 'print if $a<1; $a++ if /TLR/; ' b.txt >> 1.txt

and

$ perl -ne 'print if $a>=1; $a++ if /TLR/; ' a.txt > 2.txt
$ perl -ne 'print if $a>=1; $a++ if /TLR/; ' b.txt >> 2.txt

These simple scriptlets will add 1 to the value of the variable $a if the current line contains TLR. They then check the value of $a to decide if this line should be printed or not.

You can combine both operations into one command with:

$ perl -e '
  foreach my $file(@ARGV){
    open(my $fh,"$file"); $a=0;
    while(<$fh>){
     $a<1 ? (push @{$lines{1}},$_) : (push @{$lines{2}},$_); $a++ if /TLR/}} 
  END{open(my $fh,">","1.txt"); print $fh @{$lines{1}}; 
      open(my $fh,">","2.txt"); print $fh @{$lines{2}};}' a.txt b.txt
share|improve this answer
add comment

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.