【问题标题】:split line using string as delimiter from shell使用字符串作为 shell 的分隔符分割行
【发布时间】:2015-06-07 15:33:23
【问题描述】:

我有一个看起来像这样的文件

60 -> 36
48 -> 11
60 -> 59
35 -> 29
27 -> 76

我想将此文件拆分为两个单独的文件,分别称为源文件和目标文件,以便源文件仅包含“->”之前的元素和目标文件,之后的部分。

我尝试使用 cut 如下

cut -d' -> ' -f1 input > source
cut -d' -> ' -f2 input > destination

但是 cut 给了我这个错误

cut: the delimiter must be a single character

【问题讨论】:

    标签: shell awk sed cut


    【解决方案1】:
    awk '{print $1 > "source"; print $3 > "destination"}' input
    

    【讨论】:

      【解决方案2】:

      awk 是您进行正则表达式类型拆分的最佳选择。

      给定:

      $ echo "$tgt"  
      60 -> 36
      48 -> 11
      60 -> 59
      35 -> 29
      27 -> 76
      

      您可以在正则表达式上使用awk 拆分输入:

      $ echo "$tgt" | awk -F " -> " '{print $1}'
      60
      48
      60
      35
      27
      $ echo "$tgt" | awk -F " -> " '{print $2}'
      36
      11
      59
      29
      76
      

      并根据需要重定向到两个文件。

      【讨论】:

      • 或者在这种特殊情况下awk '{print $1}' inputawk '{print $3}' input
      • 其实不是。由于文件分隔符是" -> ",它不是$2。我在终端中使用了实际的输出...
      • @dawg 你错过了如果你使用$3 那么你不需要指定一个FS。这是“为 OP 提供他需要的东西,而不是他要求的东西”的案例之一。
      【解决方案3】:

      尝试使用空格作为分隔符:" "。在第二种情况下使用-f3

      或者使用 GNU sed:

      sed -ne 'h;s/ .*//w source' -e 'g;s/.* //w destination' input
      

      【讨论】:

        【解决方案4】:

        这样的东西可能是(gnu sed)

        sed 's/^\([^ ]*\)/\1/' <file >source  
        sed 's/.* \(.*\)/\1/' <file >destination  
        

        【讨论】:

          【解决方案5】:

          据我了解,cut 不能使用多个字符作为分隔符。

          使用sed,它应该像这样工作:

          sed -E 's/^(.*) -> .*$/\1/g' input > source
          sed -E 's/^.* -> (.*)$/\1/g' input > destination
          

          【讨论】:

            【解决方案6】:
            sed '1!H;1h;$!d
            g;s/ ->[ 0-9]*//g;w Source
            g;s/[ 0-9]* ->//g;w Destination
            ' YourFile
            

            通过删除所有行尾来写入源代码,而不是在将文件加载到内存并将其用于每个替换后删除目标行头

            【讨论】:

              猜你喜欢
              • 2013-11-23
              • 2013-05-03
              • 1970-01-01
              • 2013-08-16
              • 2021-06-12
              • 2021-12-08
              • 1970-01-01
              相关资源
              最近更新 更多