views:

275

answers:

6

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?

+2  A: 

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
Sinan Ünür
thats fine but is there a one liner for this ?
Vijay Sarathi
+4  A: 

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
VoDurden
Useless use of `cat`.
Dennis Williamson
Corrected, my bad. Still a bit new to sed.
VoDurden
nor sure why it is not working with `\s` which is replacing all "s" characters with `_`.instead i used `s/ /_/g`. this had worked like charm.but still i will accept your answer.thanks a lot for the right direction.
Vijay Sarathi
useless use of tr as well.
Odd, updated the answer to reflect this. \s should replace all white space characters. Not sure why it didn't work in your environment.
VoDurden
how could we do this without using tr as levis commented?
Vijay Sarathi
did you look through the other solutions. there's one with just sed...
+1  A: 

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()
where are you changing the case in this script?
Vijay Sarathi
+1  A: 
sed "y/ABCDEFGHIJKLMNOPQRSTUVWXYZ /abcdefghijklmnopqrstuvwxyz_/" filename
Paul Ruane
I know nothing about sed. Just curious, do we have to type all those letters? Or we can use y/[A-Z] /[a-z]_/ in sed like in Perl? Or there're some sort of shorthands?
Mike
Initially I tried y/[A-Z ]/[a-z_]/ but that did not work. I thought there may be a shorthand but I do not know of it. Hopefully someone will be able to refine my suggestion.
Paul Ruane
+11  A: 

Another Perl method:

perl -pe 'y/A-Z /a-z_/' file
Adam Bellaire
Very nice solution!
PP
+9  A: 

tr alone works:

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