Printing only the first field in a string

守給你的承諾、 提交于 2019-11-27 22:42:52

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
Suresh Anbarasan
$ 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.

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
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!