【问题标题】:Display text file stopping each line at a given character显示文本文件在给定字符处停止每一行
【发布时间】:2021-09-20 11:53:09
【问题描述】:

我有一个包含法语单词的文本文件,这里是一个例子:

hackeur -euse (n.m/f.)
huppe (n. f.) 
huque (n. f.) 
hure (n. f.)

我想显示文件,当检测到模式 ( 时停止每一行。预期的输出是:

hackeur -euse
huppe
huque
hure

我想用命令行来做这件事。可行吗?

【问题讨论】:

  • 你自己尝试了什么?
  • @Inian 没什么,我被困在互联网上搜索解决方案。我什至不确定这是否可行。

标签: shell awk sed text-processing cut


【解决方案1】:

一个使用 ( 作为字段分隔符的awk 想法:

$ awk -F' [(]' '{print $1}' french.dat
hackeur -euse
huppe
huque
hure

一些更快速的想法......

cut:

$ cut -d'(' -f1 french.dat
hackeur -euse
huppe
huque
hure

注意:这将留下一个尾随空白,可以通过其他命令(例如,sed)修剪掉

sed 和一个捕获组:

$ sed -En 's/^(.*) \(.*/\1/p' french.dat
hackeur -euse
huppe
huque
hure

注意:这假定 ( 出现一次

【讨论】:

    【解决方案2】:

    这里是基于 GNU grep的解决方案

    grep -Po '^.*?(?= \()' inputfile
    

    【讨论】:

      【解决方案3】:

      awk 可以使用 match()substr() 函数,如果你想要 each line when the pattern ( is detected

      awk 'match($0, /[(]/) {print substr($0, 1,RSTART-1)}' file
      hackeur -euse
      huppe
      huque
      hure
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-01-05
        • 1970-01-01
        • 2014-12-16
        • 2012-03-26
        • 2013-10-30
        • 1970-01-01
        相关资源
        最近更新 更多