user2099444
user2099444

Reputation: 431

Printing only the first field in a string

I have a date as 12/12/2013 14:32 I want to convert it into only 12/12/2013. The string can be 1/1/2013 12:32 or 1/10/2013 23:41 I need only the date part.

Upvotes: 42

Views: 86518

Answers (4)

RARE Kpop Manifesto
RARE Kpop Manifesto

Reputation: 2801

awk should have the most concise syntax possible, beating out cut and sed - 4 bytes of syntax, quotation completely unnecessary :

echo '12/12/2013 14:32' | 

awk NF=1

12/12/2013

Despite its extreme simplicity, the awk interpreter sees no syntax ambiguity -

— since NF=1 is the only argument after the awk command name, it wouldn't be accidentally treated as either command-line assignment, or input file name for data rows.

Upvotes: 0

Suresh Anbarasan
Suresh Anbarasan

Reputation: 1033

$ echo "12/12/2013 14:32" | awk '{print $1}'
12/12/2013

print $1 --> Prints first column of the supplied string. 12/12/2013

print $2 --> Prints second column of the supplied string. 14:32

By default, awk treats the space character as the delimiter.

Upvotes: 19

dogbane
dogbane

Reputation: 274612

If your date string is stored in a variable, then you don't need to run an external program like cut, awk or sed, because modern shells like bash can perform string manipulation directly which is more efficient.

For example, in bash:

$ s="1/10/2013 23:41"
$ echo "${s% *}"
1/10/2013

Upvotes: 5

Chris Seymour
Chris Seymour

Reputation: 85785

You can do this easily with a variety of Unix tools:

$ cut -d' ' -f1  <<< "12/12/2013 14:32"
12/12/2013

$ awk '{print $1}' <<< "12/12/2013 14:32"
12/12/2013

$ sed 's/ .*//' <<< "12/12/2013 14:32"
12/12/2013

$ grep -o "^\S\+"  <<< "12/12/2013 14:32"
12/12/2013

$ perl -lane 'print $F[0]' <<< "12/12/2013 14:32"
12/12/2013

Upvotes: 73

Related Questions