MirrG
MirrG

Reputation: 406

Including empty lines using pattern

My problem is the following: I have a text file where there are no empty lines, now I would like to include the lines according to the pattern file where 1 means print the line without including a new line, 0 - include a new line. My text file is :

apple
banana
orange
milk
bread

Thу pattern file is :

1
1
0
1
0
1
1

The desire output correspondingly:

apple
banana

orange

milk
bread

What I tried is:

for i in $(cat pattern file);
do
  awk -v var=$i '{if var==1 {print $0} else {printf "\n" }}' file;
done.

But it prints all the lines first, and only after that it changes $i

Thanks for any prompts.

Upvotes: 1

Views: 70

Answers (5)

NeronLeVelu
NeronLeVelu

Reputation: 10039

allow multiple 0 between 1

Self documented code

awk '# for file 1 only 
     NR==FNR {
      #load an array with 0 and 1 (reversed due to default value of an non existing element = 0)
      n[NR]=!$1
      # cycle to next line (don't go furthier in the script for this line)
      next
      }
     # at each line (of file 2 due to next of last bloc)
     {  
       # loop while (next due to a++) element of array = 1
       for(a++;n[a]==1;a++){
          # print an empty line
          printf( "\n")
          }
       # print the original line
       print
     }' pattern YourFile
  • need of inversion of value to avoid infinite new line on last line in case there is less info in pattern than line in data file
  • multiple 0 need a loop + test
  • unsynchro between file number of pattern and data file is a problem using a direct array (unless it keep how much newline to insert, another way to doing it)

Upvotes: 1

Grisha Levit
Grisha Levit

Reputation: 8617

For an answer using only bash:

i=0; mapfile file < file
for p in $(<pattern); do
   ((p)) && printf "%s" "${file[i++]}" || echo
done

Upvotes: 1

jas
jas

Reputation: 10865

Inverse of Barmar's, read the text into an array and then print as you process the pattern:

$ awk 'NR==FNR {fruit[NR]=$0; next} {print $0?fruit[++i]:""}' fruit.txt pattern.txt 
apple
banana

orange

milk

Upvotes: 1

ffledgling
ffledgling

Reputation: 12140

This is a bit of a hack, but I present it as an alternative to your traditionally awk-y solutions:

paste -d, file.txt <(cat pattern | tr '\n' ' ' | sed 's,1 0,10,g' | tr ' ' '\n' | tr -d '1') | tr '0' '\n' | tr -d ','

The output looks like this:

apple
banana

orange

milk
bread

Upvotes: 1

Barmar
Barmar

Reputation: 781004

Read the pattern file into an array, then use that array when processing the text file.

awk 'NR==FNR { newlines[NR] = $0; next}
     { print $0 (newlines[FNR] ? "" : "\n") }' patternfile textfile

Upvotes: 2

Related Questions