How to remove a part of a column using awk

  • awk

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

    cut -d- -f1 file
    
  • sed

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

    perl -pe 's/-.*//' file
    

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

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

Tags:

Date

Awk

Sort