Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

list lines ending with a period or semicolon

Tags:

linux

unix

how can I write a command by using grep or egrep to display all the lines in a file that end with a semicolon “;” or a period “.” character.

like image 680
femchi Avatar asked Oct 03 '12 11:10

femchi


People also ask

What is the correct command to list all the lines from the file student TXT ending with semicolon?

Answer: Command to "list all the lines" from the file "employee. txt" ending with "semi colon" is: grep ';' employee. txt. "Grep command" is used to find out the given file with specified pattern and displays all the lines matching the pattern.

How do I use grep search?

The grep command searches through the file, looking for matches to the pattern specified. To use it type grep , then the pattern we're searching for and finally the name of the file (or files) we're searching in. The output is the three lines in the file that contain the letters 'not'.


2 Answers

With grep (and egrep) a dollar sign ($) matches the end of a line, and a carret (^) matches the beginning of a line. So, for example, if you wanted to match lines containing exactly the word "fish" and no other characters you could use this:

grep '^fish$'

It's important to use single quotes to wrap the search expression so that bash doesn't do anything funny to it.

So, to answer your question, you will need to use the search pattern '[.;]$' to match either a . or ; character followed by an end of line character. I am using this as an example test file:

$ cat testfile 
one
two;
three.
four:

And here is the result:

$ grep '[.;]$' testfile 
two;
three.

If you also want to allow whitespace at the end of the line, then use this pattern: '[.;][ \t]*$' which will match with any number of spaces or tab characters after the . or ;.

like image 68
Lee Netherton Avatar answered Oct 06 '22 07:10

Lee Netherton


This should do it:

$ grep -E '(;|\.)$'

The -E switch enables regular expression mode. The expression simply matches a line ending in either a semicolon or a period.

Note: I haven't tested this.

like image 24
unwind Avatar answered Oct 06 '22 07:10

unwind