【问题标题】:AWK/SED Split a list if the row starts with OR ends with [closed]AWK/SED 如果行以 OR 开头,则拆分列表以 [关闭]
【发布时间】:2021-01-12 09:45:10
【问题描述】:

试图通过将所有符合条件的行(以 OR 结尾)重定向到一个文件中来拆分我的列表,否则在另一个文件中。 尝试使用此 AWK 但似乎无法正常工作:

awk '{print >out}; /^abc|abc.com$/{out="file2"}' out=file1 MyLargeList.lst 

任何帮助将不胜感激......

【问题讨论】:

  • awk '{print >( /^abc|abc.com$/ ? out2 : out1 )}' out1=file1 out2=file2 MyLargeList.lst

标签: regex awk sed split


【解决方案1】:

这可能对你有用(GNU sed):

sed -ne '/^abc\|abc\.com$/w file2' -e '//!w file1' file

关闭隐式打印-n

如果一行以abc 开头或以abc.com 结尾,则写入file2,否则写入file1。

或者,如果您只想分隔第一个条件,请使用:

sed '/^abc\|abc\.com$/w file2' file > file1

当然,grep 可能会更快:

grep '^abc\|abc\.com$' file > file2

grep -v '^abc\|abc\.com$' file > file1

【讨论】:

    【解决方案2】:

    这个任务的一个简单的解决方案,在一次 awk 过程中,是:

    awk '/^abc|abc\.com$/{print > "file1"; next} {print > "file2"}' file
    

    一般来说,如果您想根据多个模式匹配将行打印到多个文件中,则可以扩展到:

    awk '/pattern1/{out=f1;next} /pattern2/{out=f2;next} ... {print > out}' file
    

    您可能需要这样的默认输出(对于没有匹配的行):

    awk '... /pattern3/{out=f3;next} {out=f} {print > out}' file
    

    并且在输出很多的情况下,为了避免打开文件过多的错误,你可能需要在开头加上一个close语句:

    awk '{close(out)} /pattern1/{out=f1} ... {print > out}' file
    

    测试

    这是一个示例文件:

    > cat file
    abc
    test
    abc.com
    
    test
    test
    abc
    end
    

    结果:

    > cat file1
    abc
    abc.com
    abc
    > cat file2
    test
    
    test
    test
    end
    

    【讨论】:

      【解决方案3】:

      问题是您在第一场比赛中分配了out,然后再也不会更改它。简而言之,您似乎认为命令行上的out=file1 将在脚本的每次迭代中重新评估,但事实并非如此。

      此外,您在重新分配之前打印,因此第一个匹配项进入了错误的文件。

      awk '{ if (/^abc|abc.com$/) out="file2"
          else out="file1"
          print >out }' MyLargeList.lst
      

      正如评论中已经建议的(没有任何解释),这可以优雅但有点模糊地重新表述为使用三元布尔运算符。

      awk '{ print > (/^abc|abc.com$/ ? "file2" : "file1") }' MyLargeList.lst
      

      简而言之,如果x 为真,则x ? y : z 返回y,否则返回z

      【讨论】:

        猜你喜欢
        • 2020-10-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-25
        • 1970-01-01
        相关资源
        最近更新 更多