AWK首先打印字段$ 2,然后打印字段$ 1 [英] AWK to print field $2 first, then field $1

查看:58
本文介绍了AWK首先打印字段$ 2,然后打印字段$ 1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是输入(样本):

name1@gmail.com|com.emailclient.account
name2@msn.com|com.socialsite.auth.account

我正在努力实现这一目标:

I'm trying to achieve this:

Emailclient name1@gmail.com
Socialsite name2@msn.com

如果我这样使用AWK:

If I use AWK like this:

cat foo | awk 'BEGIN{FS="|"} {print $2 " " $1}'

通过将字段1覆盖在字段2的顶部来弄乱输出.

it messes up the output by overlaying field 1 on the top of field 2.

有任何提示/建议吗?谢谢.

Any tips/suggestions? Thank you.

推荐答案

几个常规提示(除了DOS行结尾问题):

cat用于连接文件,它不是唯一可以读取文件的工具!如果命令不读取文件,则使用command < file之类的重定向.

cat is for concatenating files, it's not the only tool that can read files! If a command doesn't read files then use redirection like command < file.

您可以使用-F选项设置字段分隔符,而不是:

You can set the field separator with the -F option so instead of:

cat foo | awk 'BEGIN{FS="|"} {print $2 " " $1}' 

尝试:

awk -F'|' '{print $2" "$1}' foo 

这将输出:

com.emailclient.account name1@gmail.com
com.socialsite.auth.accoun name2@msn.com

要获得所需的输出,您可以执行多种操作.我可能会split()第二个字段:

To get the desired output you could do a variety of things. I'd probably split() the second field:

awk -F'|' '{split($2,a,".");print a[2]" "$1}' file
emailclient name1@gmail.com
socialsite name2@msn.com

最后,要使第一个字符转换为大写字母,在awk中有点麻烦,因为您没有内置的ucfirst()函数:

Finally to get the first character converted to uppercase is a bit of a pain in awk as you don't have a nice built in ucfirst() function:

awk -F'|' '{split($2,a,".");print toupper(substr(a[2],1,1)) substr(a[2],2),$1}' file
Emailclient name1@gmail.com
Socialsite name2@msn.com

如果您想要更简洁的内容(尽管您放弃了子流程),则可以执行以下操作:

If you want something more concise (although you give up a sub-process) you could do:

awk -F'|' '{split($2,a,".");print a[2]" "$1}' file | sed 's/^./\U&/'
Emailclient name1@gmail.com
Socialsite name2@msn.com

这篇关于AWK首先打印字段$ 2,然后打印字段$ 1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆