Pergunta

Eu tenho um arquivo de texto que contém:

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

Eu quero mudar este texto de modo que sempre que há um espaço, quero substituí-lo com um _. E depois disso, eu quero que os caracteres para minúsculas letras, como abaixo:

cycle_code
cycle_month
cycle_year
event_type_id
event_id
network_start_time

Como eu poderia fazer isso?

Foi útil?

Solução

Olhando para documentação sed um pouco mais e seguir o conselho dos comentários o seguinte comando deve funcionar.

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

Outras dicas

Outro método Perl:

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

tr sozinho trabalhos:

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

Há uma tag perl na sua pergunta também. Assim:

#!/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

Ou:

perl -i.bak -wple '$_ = join('_', split ' ', lc)' test.txt
sed "y/ABCDEFGHIJKLMNOPQRSTUVWXYZ /abcdefghijklmnopqrstuvwxyz_/" filename

Basta usar o seu shell, se você tem Bash 4

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

Com gawk :

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

Com Perl:

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

Com Python:

>>> f=open("file")
>>> for line in f:
...   print '_'.join(line.split()).lower()
>>> f.close()
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top