0

I have test.txt file, which contains the lines below:

Period 1
Period 2
Period 3
........
.
.
.
Period 10
Period 11
Period 12
.
.
.

Likewise I have 18 rows inside the test.txt file.

Now I need to create the new file from this test.txt such that when I give 'Period 1', it should show only "Period 1" row alone in new file.

I am facing issue here: when I'm trying to do grep "Period 1" > newfile.txt, it gives all the period which start with "Period 1", "Period 10", "Period 11", and so on.

2
  • TRY with "Period 1 " space at the end. Commented Apr 7, 2015 at 19:40
  • Or use a regex with grep. Match the end of line character if applicable. Commented Apr 7, 2015 at 20:10

1 Answer 1

1

You should use grep with general expression, which should match the beginning and the end of the line:

grep -e '^Period 1$' > newfile.txt

The regular expression here means: "<the beginning of the line>Period<space>1<the end of the line>"

If you're not sure about format, you may use the expression, which will match any number of spaces (or any other whitespaces) in the middle:

egrep '^Period\s*1$' # egrep is synonym for `grep -E`, where -E stands for extended regexps

For further reading on regular expressions in grep: https://www.digitalocean.com/community/tutorials/using-grep-regular-expressions-to-search-for-text-patterns-in-linux

Sign up to request clarification or add additional context in comments.

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.