xiahfyj
xiahfyj

Reputation: 101

How do you change column names to lowercase with linux and store the file as it is?

I am trying to change the column names to lowercase in a csv file. I found the code to do that online but I dont know how to replace the old column names(uppercase) with new column names(lowercase) in the original file. I did something like this: $cat head -n1 xxx.csv | tr "[A-Z]" "[a-z]"

But it simply just prints out the column names in lowercase, which is not enough for me. I tried to add sed -i but it did not do any good. Thanks!!

Upvotes: 0

Views: 406

Answers (3)

Gilles Quénot
Gilles Quénot

Reputation: 185189

Using :

perl -i -pe '$_=lc() if $.==1' file.csv

It replace the file on the fly with -i switch

Upvotes: 1

Gilles Quénot
Gilles Quénot

Reputation: 185189

Using (readability winner) :

concise way:

awk 'NR==1{print tolower($0);next}1' file.csv

or using ternary operator:

awk '{print (NR==1) ? tolower($0): $0}' file.csv

or using if/else statements:

awk '{if (NR==1) {print tolower($0)} else {print $0}}' file.csv

To change the file for real:

awk 'NR==1{print tolower($0);next}1' file.csv | tee /tmp/temp
mv /tmp/temp file.csv

For your information, using the in place edit switch -i do the same: it use a temporary file under the hood.

You can check this by using :

strace -f -s 800 sed -i'' '...' file

Upvotes: 1

SiegeX
SiegeX

Reputation: 140367

You can use sed to tell it to replace the first line with all lower-case and then print the rest as-is:

sed '1s/.*/\L&/' ./xxx.csv

Redirect the output or use -i to do an in-place edit.

Proof of Concept

$ echo -e "COL1,COL2,COL3\nFoO,bAr,baZ" | sed '1s/.*/\L&/'
col1,col2,col3
FoO,bAr,baZ

Upvotes: 0

Related Questions