6

I have a file that has lines of numbers and a file:

    2    20    3    file1.txt
    93   21    42   file2.txt
    52   10    12   file3.txt

How do I use grep, awk, or some other command to just give me the first numbers of each line so that it will only display:

2
93
52

Thanks.

Arnold Hotz
  • 179
  • 1
  • 3
  • 8

3 Answers3

9

So many ways to do this. Here are some (assuming the input file is gash.txt):

awk '{print $1}' gash.txt

or using pure bash:

while read num rest
do
    echo $num
done < gash.txt

or using "classic" sed:

sed 's/[ \t]*\([0-9]\{1,\}\).*/\1/' gash.txt

or using ERE with sed:

sed -E 's/[ \t]*([0-9]+).*/\1/' gash.txt

Using cut is problematic because we don't know if the whitespace is spaces or tabs.

By the way, if you want to add the total number of lines:

awk '{total+=$1} END{print "Total:",total}' gash.txt
cdarke
  • 42,728
  • 8
  • 80
  • 84
6

You can use this:

grep -oE '^\s*[0-9]+' filename

To handle the leading spaces, I'm currently out of options. You better accept the awk answer.

blackSmith
  • 3,054
  • 1
  • 20
  • 37
2

You can use awk

awk '{print $1}' file 
oliv
  • 12,690
  • 25
  • 45