【问题标题】:How can I change spaces to underscores and lowercase everything?如何将空格更改为下划线和小写所有内容?
【发布时间】:2009-11-27 12:42:48
【问题描述】:

我有一个文本文件,其中包含:

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 或 awk”还是“sed、awk 或 Perl”?
  • 任何可以解决我问题的方法

标签: perl shell sed awk


【解决方案1】:

另一种 Perl 方法:

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

【讨论】:

    【解决方案2】:

    tr 单独工作:

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

    【讨论】:

      【解决方案3】:

      更多地查看 sed 文档并遵循 cmets 的建议,以下命令应该可以工作。

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

      【讨论】:

      • 已更正,我的错。 sed 还是有点新意。
      • 也不知道为什么它不能与\s 一起使用,它用_ 替换所有“s”字符。相反,我使用了s/ /_/g。这就像魅力一样。但我仍然会接受你的回答。非常感谢正确的方向。
      • 奇怪,更新了答案以反映这一点。 \s 应该替换所有空白字符。不知道为什么它在您的环境中不起作用。
      • 不使用 tr levis 评论我们怎么能做到这一点?
      【解决方案4】:

      您的问题中也有一个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
      

      【讨论】:

      • 没关系,但有没有一个衬里?
      【解决方案5】:
      sed "y/ABCDEFGHIJKLMNOPQRSTUVWXYZ /abcdefghijklmnopqrstuvwxyz_/" filename
      

      【讨论】:

      • 我对 sed 一无所知。只是好奇,我们必须输入所有这些字母吗?或者我们可以像在 Perl 中一样在 sed 中使用 y/[A-Z] /[a-z]_/ ?还是有某种速记?
      • 最初我尝试了 y/[A-Z ]/[a-z_]/ 但没有奏效。我想可能有一个速记,但我不知道。希望有人能够完善我的建议。
      【解决方案6】:

      只要使用你的 shell,如果你有 Bash 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()
      

      【讨论】:

      • 你在这个脚本的哪里改变大小写?
      猜你喜欢
      • 2017-10-26
      • 2012-03-16
      • 1970-01-01
      • 2020-11-04
      • 1970-01-01
      • 2021-12-03
      • 1970-01-01
      • 2020-05-25
      • 2015-11-03
      相关资源
      最近更新 更多