bash 如何使用 awk 将文件的某个字段更改为大写?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14022529/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I change a certain field of a file into upper-case using awk?
提问by Yishu Fang
I have a text file like this:
我有一个这样的文本文件:
1 http http 3 4 5
2 dns dns 4
3 ftp ftp 4 5 6 8
I want the output to be like this:
我希望输出是这样的:
1 HTTP http 3 4 5
2 DNS dns 4
3 FTP ftp 4 5 6 8
I want to change the second field from lower-case into upper-case and only the second field.
我想将第二个字段从小写更改为大写,并且只更改第二个字段。
Note that the number of fields in a certain line is not fixed.
请注意,某一行中的字段数不是固定的。
Can I accomplish this goal using awk?
我可以使用awk?
回答by Steve
You sure can. Here's how:
你肯定可以。就是这样:
awk ' = toupper()' file
Results:
结果:
1 HTTP http 3 4 5
2 DNS dns 4
3 FTP ftp 4 5 6 8
From the manual:
从手册:
tolower(str)
Returns a copy of the string str, with all the upper-case characters in str translated to their corresponding lower-case counterparts. Non-alphabetic characters are left unchanged.
toupper(str)
Returns a copy of the string str, with all the lower-case characters in str translated to their corresponding upper-case counterparts. Non-alphabetic characters are left unchanged.
降低(str)
返回字符串 str 的副本,并将 str 中的所有大写字符转换为相应的小写字母。非字母字符保持不变。
上衣(字符串)
返回字符串 str 的副本,其中 str 中的所有小写字符都转换为相应的大写字母。非字母字符保持不变。
I made the assumption that given your sample data, it would have at least three columns and that the variable component you discuss applies to the columns after those containing words. If I was wrong, you can simply add the conditional:
我假设给定您的示例数据,它至少有三列,并且您讨论的变量组件适用于包含单词的列之后的列。如果我错了,您可以简单地添加条件:
awk 'NF>1 { = toupper() }1' file
回答by Vijay
perl -F -ane '$F[1] = lc($F[1]);print "@F"' your_file

