3

I have a file, my_file. The contents of the file look like this:

4: something
5: something
7: another thing

I want to print out the following:

4
5
7

Basically I want to get all the numbers before the character :

Here is what I tried:

grep -i "^[0-9]+(?=(:)" my_file

This returned nothing. How can I change this command to make it work?

JVM
  • 99
  • 1
  • 5
  • Does this answer your question? [Can grep show only words that match search pattern?](https://stackoverflow.com/questions/1546711/can-grep-show-only-words-that-match-search-pattern) – bhristov May 27 '20 at 04:27
  • 3
    This seems like a duplicate of: [How can i print the all the characters until a certain pattern(excluding the pattern itself) using grep/awk/sed.](https://stackoverflow.com/questions/12360942/how-can-i-print-the-all-the-characters-until-a-certain-patternexcluding-the-pat) (`grep -o '^[^:]*'` works for your input), if you're looking for a PCRE-specific solution, state it explicitly in the question – oguz ismail May 27 '20 at 04:50
  • @oguzismail grep -o '^[^:]*' won't work if there is a single letter that begins the line. It seems that the OP is asking for a PCRE. – bhristov May 27 '20 at 05:14
  • @bhristov I don't understand what you're saying. – oguz ismail May 27 '20 at 06:15
  • For example, if we have a line that starts with a letter: a123: This will be matched by that regex. – bhristov May 27 '20 at 06:17

3 Answers3

3

This is a use-case for awk:

$ awk -F":" '{print $1}' < inputfile

because you're using : as a field delimiter.

James McPherson
  • 2,476
  • 1
  • 12
  • 16
2

Try this:

grep -Eo "^[0-9]+" my_file # you can use either E (extended) or P (pearl) regular expressions

-o is for only matching

We also need to specify that we are using regex.

Both of the following will work: -E extended regular expressions -P pearl regular expressions

Breakdown:

^  signifies the start
  [0-9]  match a digit
       +  match 1 or more from [0-9]

Output:

4
5
7
halfer
  • 19,824
  • 17
  • 99
  • 186
bhristov
  • 3,137
  • 2
  • 10
  • 26
0

Using grep


grep -oE '^[0-9]+:' my_file |  tr -d ':'

using sed

sed 's#:.*$##g' my_file

Demo :

$cat test.txt 
4: something
5: something
7: another thing
$sed 's#:.*$##g' test.txt
4
5
7
$grep -oE '^[0-9]+:' test.txt |  tr -d ':'
4
5
7
Digvijay S
  • 2,665
  • 1
  • 9
  • 21