-1

I have many files on UNIX and wish to fetch number in that file associated with a specified pattern.

Most of the file will have a unique pattern in file like below

some text abc
some text abc
some text abc
(3 rows)

The number could vary from file to file, it could be 35644 or any numeric value as well.

I want to find that number using grep or sed not awk. so far I was able to get this. I want to do this using single line unix command including redirection if applicable.

grep 'rows' file.txt

Edit - Removed the requirement if pattern is not found what should happen.

  • So, are you saying that your example file is four lines long, and the fourth line contains the text (3 rows)?  And that you want to extract the 3 from the (3 rows) line (regardless of the actual number of lines in the file)?  Do you guarantee that only one row in the file contains the word row — or that only one line will begin with (, followed by a sequence of digits, followed by a space and rows)? (If there are only two lines in the file, will the second one say (1 row) or (1 rows)?) Please do not respond in comments; edit your question to make it clearer and more complete. – G-Man Jan 22 '18 at 6:34
  • That one row will begin with (numbercount rows) and will have this pattern. It might possible rows might come as string somewhere else but not as this pattern (numbercount rows). – Minsec Jan 22 '18 at 6:44
0
sed -n -e 's/^(\([0-9]\+\) rows)$/\1/p'

This prints the digits immediately following the ( on lines that contain only (nnn rows) (where nnn is any positive integer).

No other lines are printed.

  • I tried this by specifying file name with pattern didn'print anything. sed -n -e 's/^(\([0-9]\+\) rows)$/\1/p' file.txt – Minsec Jan 22 '18 at 6:54
  • then your file doesn't match what you specified in your question. did your files come from a windows machine? (i.e. do they have CR+LF line endings rather than unix-style LF-only?). Try adding \r\? immediately before the $ in the sed script - that will match either unix or windows line-endings. or convert them to unix text files with fromdos or similar. – cas Jan 22 '18 at 6:58
  • file is created in unix only with LF style. – Minsec Jan 22 '18 at 7:00
  • then what you stated in your question is incorrect - it does not accurately describe your files. I tested it before I posted using the sample text you provided and it printed 3. – cas Jan 22 '18 at 7:01
  • I'm on HP UNIX will sed command differ all versions of UNIX? As command is getting executed successfully but doesn't print anything. My requirement is clear and same as what I have posted. – Minsec Jan 22 '18 at 7:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.