【问题标题】:Remove numbers after colon [duplicate]删除冒号后的数字[重复]
【发布时间】:2017-04-22 01:34:23
【问题描述】:

我有一个文件如下:

1:01
4:04
7:07
5:05
3:03

一般模式是<a number>:0<the same number before colon>。我想删除冒号和冒号后的所有内容。这会产生。

1
4
7
5
3

在 bash 或 python 中实现这一目标的简单方法是什么。

【问题讨论】:

  • awk -F: '{ print $1 }'

标签: python bash awk


【解决方案1】:

Python 方式:

将输入作为字符串列表,比如

>>>input = ['1:01', '4:04', '7:07', '5:05', '3:03']

使用split 和列表推导创建一个包含所需输出的列表

>>>output = [i.split(':')[0] for i in input]

现在你有了所需的输出:

>>>output
['1', '4', '7', '5', '3']

【讨论】:

  • Pythonic 将是 output = [x.split(':')[0] for x in input]
  • 是的,这样更好。
【解决方案2】:

嗯,如果和你的例子一模一样的话-

awk -F: '{print $1}' file

-F 标志将分隔符设置为:print $1 询问冒号前的内容,这就是您想要的。

【讨论】:

  • 就地编辑它,gawk -i inplace -F: '{print $1}' file 会成功吗?或者有没有更好的方法来使用 awk 就地编辑?
  • 是的。否则你甚至可以做-awk -F: '{print $1}' file > temp ; mv temp file
【解决方案3】:

使用cut

cut -d':' -f1 file

【讨论】:

  • 再来一次!同样的想法,同样的时间:D
【解决方案4】:

这是cut 命令的工作:

cut -d: -f1 input.file

【讨论】:

    【解决方案5】:

    Python:

    text= '1:01'
    sep = ':'
    rest = text.split(sep, 1)[0]
    
    Out: 
    
    1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-08
      • 1970-01-01
      • 2011-05-25
      • 1970-01-01
      • 2012-10-01
      • 1970-01-01
      • 2012-08-28
      • 2016-10-03
      相关资源
      最近更新 更多