0

I have a large file that looks something like this:

line1
line2
line3;

line5
line6;
line7

line9
line10;

Basically, it's a bunch of lines, some of which end in semicolons. There may or may not be empty lines after these lines with semicolons.

I'd like to do something that seems relatively simple with this file, but I haven't been able to come up with a way to do it. I'd like to invoke a bash script that would identify those lines that end with semicolons and echo the first nonempty line after each of them.

So, in the example above, the output would be:

line5
line7

I've tried a few different ways, including looping through the whole file, using a regex to check if the current line ends in a semicolon, and toggling a boolean variable to determine if the next nonempty line should be echoed. But I haven't had any luck.

It seems like there should be any easier way, perhaps using grep, but I can't seem to come up with it. Any ideas on a good way to implement this?

2
  • Will there be two consecutive lines ending with ';' you need the first non-empty line after ';' or the first non-empty line not ending with ';'? Commented Dec 5, 2013 at 3:44
  • Good question. There could be two consecutive lines ending with ';'. If this is the case, I would want that second line. So I'm looking for the first non-empty line after ';', regardless of whether it has a ';' or not. Commented Dec 5, 2013 at 4:40

4 Answers 4

1

Awk is pretty good for this sort of thing.

$ cat data
line1
line2
line3;

line5
line6;
line7

line9
line10;
$ awk '/;$/{print_next=1; next} (/^[^ ].*$/ && print_next) {print; print_next=0}' < data
line5
line7
Sign up to request clarification or add additional context in comments.

Comments

1

Try this command:

sed '/^$/d' file | sed -n '/;/{n;p}'
  • remove empty lines
  • print lines bellow ;

Comments

0

Incase you want "grep" only solution

grep -v "^$" file | grep -A1 ";" | grep -v ";\|--"

Comments

0

Try "sed -e '/;$/d' test.txt" command, its working.

 # cat test.txt 
 line1
 line2
 line3;

 line5
 line6;
 line7

 line9
 line10;


 # sed -e '/;$/d' test.txt > lines.txt

 # cat lines.txt 
 line1
 line2

 line5
 line7

 line9

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.