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.
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.
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'.
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 ;
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With