如何将空格更改为下划线和小写字母?
我有一个包含一个文本文件:如何将空格更改为下划线和小写字母?
Cycle code
Cycle month
Cycle year
Event type ID
Event ID
Network start time
我想,这样,当曾经有一个空间,我想用一个_
来代替它来改变这个文本。在这之后,我想的字符小写字母象下面这样:
cycle_code
cycle_month
cycle_year
event_type_id
event_id
network_start_time
我怎么能做到这一点?
展望sed的文档多一些及继起的下列命令应该工作的意见建议。
sed -r {filehere} -e 's/[A-Z]/\L&/g;s/ /_/g' -i
无用的'猫'。 – 2009-11-27 12:52:27
更正,我的不好。 sed还有点新意。 – 2009-11-27 12:55:26
也不知道为什么它不能用'\ s'替换所有's'字符'''而不是's// _/g'。这已经像魅力一样工作了,但我仍然会接受你的回答。感谢你的正确方向。 – Vijay 2009-11-27 13:00:04
在你的问题中还有一个perl
标签。所以:
#!/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
或者:
perl -i.bak -wple '$_ = join('_', split ' ', lc)' test.txt
多数民众赞成在罚款,但有没有一个这样的班轮? – Vijay 2009-11-27 12:51:25
只需使用你的shell,如果你有击4
while read -r line
do
line=${line,,} #change to lowercase
echo ${line// /_}
done < "file" > newfile
mv newfile file
随着gawk:
awk '{$0=tolower($0);$1=$1}1' OFS="_" file
用Perl:
perl -ne 's/ +/_/g;print lc' file
使用Python:
>>> f=open("file")
>>> for line in f:
... print '_'.join(line.split()).lower()
>>> f.close()
你在哪里改变这个脚本的情况? – Vijay 2009-11-27 13:01:23
sed "y/ABCDEFGHIJKLMNOPQRSTUVWXYZ /abcdefghijklmnopqrstuvwxyz_/" filename
我对sed一无所知。只是好奇,我们是否必须输入所有这些信件?或者我们可以像使用Perl一样在sed中使用y/[A-Z]/[a-z] _ /?或者有某种短命? – Mike 2009-11-27 13:37:36
最初我尝试过y/[A-Z]/[a-z _] /但没有奏效。我想可能有一个速记,但我不知道它。希望有人能够改进我的建议。 – 2009-11-27 14:46:42
另一个Perl的方法:
perl -pe 'y/A-Z /a-z_/' file
非常好的解决方案! – 2009-11-27 14:14:31
tr
单独作品:
tr ' [:upper:]' '_[:lower:]' < file
是 “awk或者sed” 或 “sed中,AWK或Perl”? – innaM 2009-11-27 12:46:42
什么都可以解决我的问题 – Vijay 2009-11-27 12:49:14