【问题标题】:extract rows from text file and save it in separate files从文本文件中提取行并将其保存在单独的文件中
【发布时间】:2021-02-13 22:54:35
【问题描述】:

我有一个非常大的文本文件,我想从中提取每两行并希望将其保存在单独的文件中,文件名应保存在名称 firstrowfirstcolumn_firstrowfourthcolumn 中

10  25  6  3  1  8  5  2  1  6  1
99  26  7  4  1  8  8  1  2  8  1
11  25  6  8  1  8  5  2  1  6  1
99  26  7  4  1  8  8  1  2  8  1
12  25  6  3  1  8  5  2  1  6  1
99  26  7  4  1  8  8  1  2  8  1
13  25  6  3  1  8  5  2  1  6  1
99  26  7  4  1  8  8  1  2  8  1
14  25  6  3  1  8  5  2  1  6  1
99  26  7  4  1  8  8  1  2  8  1
15  25  6  4  1  8  5  2  1  6  1
99  26  7  4  1  8  8  1  2  8  1
16  25  6  4  1  8  5  2  1  6  1
99  26  7  4  1  8  8  1  2  8  1
17  25  6  4  1  8  5  2  1  6  1
99  26  7  4  1  8  8  1  2  8  1
18  25  6  4  1  8  5  2  1  6  1
99  26  7  4  1  8  8  1  2  8  1
19  25  6  4  1  8  5  2  1  6  1
99  26  7  4  1  8  8  1  2  8  1
20  25  6  5  1  8  5  2  1  6  1
99  26  7  4  1  8  8  1  2  8  1

例如 10_3.txt 应该包含

10  25  6  3  1  8  5  2  1  6  1
99  26  7  4  1  8  8  1  2  8  1

同样应该包含 11_8.txt

11  25  6  8  1  8  5  2  1  6  1
99  26  7  4  1  8  8  1  2  8  1

同样应包含 12_3.txt

12  25  6  3  1  8  5  2  1  6  1
99  26  7  4  1  8  8  1  2  8  1

等等

我尝试了下面的代码,但它不起作用

for file in input
do
awk 'NR==1,NR==2' $file
done

【问题讨论】:

    标签: linux shell for-loop awk while-loop


    【解决方案1】:

    另一个 awk

    $ awk ' { fn=$1 "_" $4 ".txt" ; print > fn; getline ;print > fn }' glk.txt
    $ cat 10_3.txt
    10  25  6  3  1  8  5  2  1  6  1
    99  26  7  4  1  8  8  1  2  8  1
    $ cat 11_8.txt
    11  25  6  8  1  8  5  2  1  6  1
    99  26  7  4  1  8  8  1  2  8  1
    $ cat 12_3.txt
    12  25  6  3  1  8  5  2  1  6  1
    99  26  7  4  1  8  8  1  2  8  1
    $
    

    【讨论】:

      【解决方案2】:

      您能否尝试以下操作,完全基于您显示的示例。写在手机上所以无法测试,我相信应该可以工作。

      awk '
      FNR%2!=0{
        close(output_file)
        output_file=$1"_"$4".txt"
      }
      {
        print > (output_file)
      }' Input_file
      

      或制作 2 个变量,您需要将其作为输出文件名。

      awk -v first="1" -v second="4" '
      FNR%2!=0{
        close(output_file)
        output_file=$first"_"$second".txt"
      }
      {
        print > (output_file)
      }' Input_file
      

      简要说明: 只需检查行号是否为奇数的条件,然后关闭先前的输出文件并根据当前行的字段创建新的输出文件名,然后打印该输出文件的所有内容。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-24
        • 1970-01-01
        • 2017-11-02
        • 2019-03-04
        • 1970-01-01
        相关资源
        最近更新 更多