Home > Software design >  in shell script how to print a line if the previous and the next line has a blank and the
in shell script how to print a line if the previous and the next line has a blank and the

Time:09-22

I have a file like

abc  
1234567890  
0987654321

cde

fgh

ijk  
1234567890  
0987654321  

I need to write a script that extract the lines with a blank before and after, in the example should be like this:

cde
fgh

I guess that awk or sed could do the work but I wasn't able to make them work. Any help?

CodePudding user response:

Here is the solution.

#!/bin/bash
amt=$(sed -n '$=' path-to-your-file)
i=0
while :
do
  ((i  ))
  if [ $i == $amt ]; then
    break
  fi
  if ! [ $i == 1 ]; then
    j=$(expr $i - 1)
    emp=$(sed $j'!d' path-to-your-file)
    if [ h$emp == h ]; then
      j=$(expr $i   1)
      emp=$(sed $j'!d' path-to-your-file)
      if [ h$emp == h ]; then
        emp=$(sed $i'!d' path-to-your-file)
        echo >> extracted $emp
      fi
    fi
  fi
done

CodePudding user response:

With awk:

awk '
BEGIN{
    RS=""
    FS="\n"
    }
NF==1' file

Prints:

cde
fgh

CodePudding user response:

very simple solution

 cat "myfile.txt" | grep -A 1 '^$' | grep -B 1 '^$' | grep -v -e '^--$' | grep -v '^$'

assuming "--" is the default group separator

you may get ride of group separator by other means like --group-separator="" or --no-group-separator options but depends of grep program variant (BSD, Gnu, OSX... )

  • Related