5

I have this :

2018:01:02-23:52:48
2018:01:02-23:52:48
2018:01:02-23:52:48
2018:01:03-09:26:20
2018:01:03-09:26:20

I want to keep the date, but not the hour in order to sort the number of messages per day :

2018:01:02
2018:01:02
2018:01:02
2018:01:03
2018:01:03

I want to do it with awk if possible.

  • If this is the only data in your file then "awk -F- '{ print $1 }' filename" should do it. – Raman Sailopal Jan 8 '18 at 10:52
13
  • awk

    awk -F- '$0=$1' file
    
  • cut

    cut -d- -f1 file
    
  • sed

    sed 's/-.*//' file
    
  • perl

    perl -pe 's/-.*//' file
    
  • 3
    Cut is the right tool, +1 :) – Ikaros Jan 8 '18 at 13:52
  • 1
    cut is the right tool if that's the one and only thing you want to do with the input lines. if you want to do anything else as well, use awk or perl. or even sed. – cas Jan 9 '18 at 4:45
7

Simply with awk:

awk -F'-' '{ print $1 }' file
  • -F'-' - treat - (dash) as field separator

But in your simple case grep approach would be even simpler:

grep -o '^[^-]*' file
  • I forgot to write that I already tried this specific awk command. And it doesn't work.. – Namless Jan 8 '18 at 11:00
  • @Namless, make sure you have posted the actual input and check your code for errors – RomanPerekhrest Jan 8 '18 at 11:27
4

If the input only contains the timestamps, then it's easy to set the dash as the field separator and only print the first field:

$ awk -F- '{print $1}' input
2018:01:02
2018:01:02

But if you also have something else in there, say input2 contains

2018:01:02-23:52:48 some data 
2018:01:02-23:52:48 something else

then that would drop the rest of the line, and for other processing, you might not want to change the field separator either. But you can do a simple substitution on the first field and print the resulting line:

$ awk '{sub(/-.*/, "", $1)} 1' input2
2018:01:02 some data
2018:01:02 something else
2
awk -F- ' { print $1 } ' | sort | uniq -c

Will also do the summation for you:

  3 2018:01:02
  2 2018:01:03
0

I achieved the same by below awk substring method

 awk '{print substr($1,1,10)}'  filename

Output

2018:01:02
2018:01:02
2018:01:02
2018:01:03
2018:01:03
0

by gnu awk

$ awk 'BEGIN{FS="[:-]"} {print $1":"$2":"$3 }' file

or

$ awk 'BEGIN{FPAT="[0-9]+"}{print $1":"$2":"$3 }' file

may change date separator printout above to one liking

$ awk 'BEGIN{FS="[:-]"}{print $1"/"$2"/"$3 }' file
2018/01/02
2018/01/02
2018/01/02
2018/01/03
2018/01/03
0

Done in python

#!/usr/bin/python
import subprocess
import re
h=open('filename','r')
for  i in h:
    print i.split('-')[0].strip()

output

2018:01:02
2018:01:02
2018:01:02
2018:01:03
2018:01: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.