Vijay
Vijay

Reputation: 67211

How can I change spaces to underscores and lowercase everything?

I have a text file which contains:

Cycle code
Cycle month
Cycle year
Event type ID
Event ID
Network start time

I want to change this text so that when ever there is a space, I want to replace it with a _. And after that, I want the characters to lower case letter like below:

cycle_code
cycle_month
cycle_year
event_type_id
event_id
network_start_time

How could I accomplish this?

Upvotes: 0

Views: 2924

Answers (6)

Jake Woods
Jake Woods

Reputation: 1828

Looking into sed documentation some more and following advice from the comments the following command should work.

sed -r {filehere} -e 's/[A-Z]/\L&/g;s/ /_/g' -i

Upvotes: 4

ghostdog74
ghostdog74

Reputation: 342273

Just use your shell, if you have Bash 4

while read -r line
do
    line=${line,,} #change to lowercase
    echo ${line// /_}
done < "file"  > newfile
mv newfile file

With gawk:

awk '{$0=tolower($0);$1=$1}1' OFS="_" file

With Perl:

perl -ne 's/ +/_/g;print lc' file

With Python:

>>> f=open("file")
>>> for line in f:
...   print '_'.join(line.split()).lower()
>>> f.close()

Upvotes: 1

mouviciel
mouviciel

Reputation: 67831

tr alone works:

tr ' [:upper:]' '_[:lower:]' < file

Upvotes: 11

Adam Bellaire
Adam Bellaire

Reputation: 110429

Another Perl method:

perl -pe 'y/A-Z /a-z_/' file

Upvotes: 12

Paul Ruane
Paul Ruane

Reputation: 38580

sed "y/ABCDEFGHIJKLMNOPQRSTUVWXYZ /abcdefghijklmnopqrstuvwxyz_/" filename

Upvotes: 1

Sinan &#220;n&#252;r
Sinan &#220;n&#252;r

Reputation: 118118

There is a perl tag in your question as well. So:

#!/usr/bin/perl

use strict; use warnings;

while (<DATA>) {
    print join('_', split ' ', lc), "\n";
}
__DATA__
Cycle code
Cycle month
Cycle year
Event type ID
Event ID
Network start time

Or:

perl -i.bak -wple '$_ = join('_', split ' ', lc)' test.txt

Upvotes: 3

Related Questions