Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change a certain field of a file into upper-case using awk?

Tags:

linux

bash

awk

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?

like image 351
Yishu Fang Avatar asked Dec 24 '12 14:12

Yishu Fang


1 Answers

You sure can. Here's how:

awk '$2 = toupper($2)' 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.


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 { $2 = toupper($2) }1' file
like image 56
Steve Avatar answered Sep 28 '22 09:09

Steve