【问题标题】:Print requested lines from multiple files从多个文件打印请求的行
【发布时间】:2015-12-23 02:22:37
【问题描述】:

我想从多个文件中获取特定的行。

我试过这样做:

sed -n "5p;10p" file1.txt file2.txt

但它只打印第一个文件中的行,有人有解决方案吗? 谢谢

【问题讨论】:

  • sed 不区分多个文件并将它们全部视为一个流。
  • @karakfa :哎呀,从来没有遇到过。像往常一样,is 有一个 awk 解决方案 ;-) 删除我之前的评论。感谢分享!

标签: awk sed


【解决方案1】:

awk 来救援!

$ awk 'FNR==5 || FNR==10' file{1,2}.txt

将从两个文件中打印第 5 行和第 10 行。

或者,每 5 行,很容易 (5,10,15,...)

$ awk '!(FNR%5)' file{1,2}.txt

或者,质数行

$ awk '{for(i=2;i<=sqrt(NR);i++) if(!(NR%i)) next} NR>1' file{1,2}.txt

【讨论】:

    【解决方案2】:

    如果您使用的是 GNU sed,则可以使用 -s 开关。来自手册:

    '-s' '--separate'
         By default, 'sed' will consider the files specified on the command
         line as a single continuous long stream.  This GNU 'sed' extension
         allows the user to consider them as separate files: range
         addresses (such as '/abc/,/def/') are not allowed to span several
         files, line numbers are relative to the start of each file, '$'
         refers to the last line of each file, and files invoked from the
         'R' commands are rewound at the start of each file.
    

    【讨论】:

    • 很好,我不知道这个!对于那些在 OSX 上的用户,您可以使用 homebrew 安装 gnu-sed 并以gsed 访问它。
    • 值得知道-i开关使用-s开关幕后
    【解决方案3】:

    我猜sed 是在处理这些文件之前连接它们。试试这样的:

    for f in file1.txt file2.txt; do
        sed -n "5p;10p" $f
    done
    

    【讨论】:

      【解决方案4】:

      sed 用于在单个行上进行简单替换,仅此而已。对于其他任何事情,您都应该使用 awk。这个问题不是在单个行上的简单替换,因此您不应该使用 sed,而应该使用 awk:

      $ cat tst.awk
      BEGIN {
          split(lines,tmp,/,/)
          for (i in tmp) {
              split(tmp[i],range,/-/)
              j = range[1]
              do {
                  fnrs[j]
              } while (j++<range[2])
          }
      }
      FNR in fnrs { print FILENAME, FNR, $0 }
      
      $ paste file1 file2
      a       A
      b       B
      c       C
      d       D
      e       E
      f       F
      g       G
      
      $ awk -v lines="2,4-6" -f tst.awk file1 file2
      file1 2 b
      file1 4 d
      file1 5 e
      file1 6 f
      file2 2 B
      file2 4 D
      file2 5 E
      file2 6 F
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-30
        • 1970-01-01
        • 2015-10-04
        • 2017-07-03
        • 1970-01-01
        • 2014-01-06
        相关资源
        最近更新 更多