Grep everything before a specific character

Viewed 4707

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?

3 Answers

This is a use-case for awk:

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

because you're using : as a field delimiter.

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

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
Related