【问题标题】:Remove all character after matched character删除匹配字符后的所有字符
【发布时间】:2014-12-04 01:41:18
【问题描述】:

我有一个包含很多行的文件

http://example.com/part-1   this    number 1 one 
http://example.com/part--2  this is number 21 two
http://example.com/part10   this is an number 12 ten
http://example.com/part-num-11  this is an axample  number 212 eleven

如何删除第一列和“数字 x”之间的“数字 x”+ 之后的所有字符...我想要这样的输出

http://example.com/part-1    1
http://example.com/part--2   21 
http://example.com/part10    12
http://example.com/part-num-11   212 

另一种情况: 输入:

http://server1.example.com/00/part-1    this    number 1 one 
http://server2.example.com/1a/part--2   this is section 21 two two
http://server3.example.com/2014/5/part10    this is an Part 12 ten  ten ten
http://server5.example.com/2014/7/part-num-11   this is an PARt number 212 eleven

我想要相同的输出....而且数字总是在最后一个数字字段中

【问题讨论】:

    标签: awk sed grep


    【解决方案1】:

    这是一种方法:

    awk -F"number" '{split($1,a," ");split($2,b," ");print a[1],b[1]}' file
    http://example.com/part-1 1
    http://example.com/part--2 21
    http://example.com/part10 12
    http://example.com/part-num-11 212
    

    如果你喜欢的数字总是在倒数第二个字段上,这也应该这样做:

    awk '{print $1,$(NF-1)}' file
    http://example.com/part-1 1
    http://example.com/part--2 21
    http://example.com/part10 12
    http://example.com/part-num-11 212
    

    【讨论】:

      【解决方案2】:
      sed -r 's/^([^0-9]*[0-9]+)[^0-9]*([0-9]+).*/\1 \2/' file
      

      输出:

      http://example.com/part-1 1 http://example.com/part--2 21 http://example.com/part10 12 http://example.com/part-num-11 212

      【讨论】:

        【解决方案3】:

        试试这个:

        sed 's/ .*number \([0-9]+\).*/ \1/' myfile.txt
        

        【讨论】:

          【解决方案4】:

          谢谢大家...从你们的cmets,我有自己的解决方案:

          sed -re 's/([0-9]*[0-9]+)/#\1#/g' | sed -re 's/(^.*#).*/\1/g' | sed 's/#//g' | awk '{print $1"  "$NF}'
          

          我的想法:用 #[numbers]# 替换所有数字组,然后选择从行首到“#”的所有字符(sed 将选择最后一个 # )并删除所有剩余字符。接下来是awk

          谢谢大家(y)

          【讨论】:

          • 没有。将一堆命令和管道链接在一起做这样一件微不足道的事情并不是正确的方法。使用发布的任何其他解决方案,如果您不喜欢其中任何一个,请告诉我们,因为还有其他几个简单的单命令解决方案。
          • 我的真实案例比这更复杂,每行都包含 unicode 字符串......
          • 与使用一个命令相比,一系列单独的命令以某种方式通过管道连接在一起可以帮助您解决这个问题?
          • 我在第二个例子中想要什么:第一列和带数字的列...但是带数字的列在每一行都不同...那么,您对我的情况有什么解决方案吗?
          • 对不起,我不知道你在说什么。
          猜你喜欢
          • 1970-01-01
          • 2018-05-31
          • 2018-09-10
          • 1970-01-01
          • 1970-01-01
          • 2015-12-02
          • 1970-01-01
          • 2016-01-02
          • 2020-07-11
          相关资源
          最近更新 更多