首页 > 解决方案 > 使用 shell 脚本操作文本文件

问题描述

我将输入数据保存在文本文件(input.txt)中,如下所示

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

我只需要在第一列的第一行每增加 5 次后将第 4 列的第一行值(3)增加一个,我不想打扰第二行例如,如果我将上述数据作为输入,则预期输出将会

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 3    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

之后,我想将第一行第 4 列值的值增加 1,因此 3 在那时为 4 输出应如下所示

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

依此类推,下面给出了我的脚本,它给出了输出但不符合我的期望,我希望我可以从专家那里得到一些想法。

#!/bin/sh
for inc in $(seq 10 1 60)
do
  awk -vval=$inc '{
    if(NR==1) {
      $1=val
    } else $4=$4;
    print
  }' input.txt
echo '>>>>'
done

标签: linuxshellfor-loopawk

解决方案


你的问题不是很清楚,这个解决方案完全基于你显示的预期样本输出。解决方案有 2 个awk变量times,表示您要打印整个文件集的次数,并thr表示您希望在 Input_file 的第一行中增加第 4 列的值的阈值是多少。如果这是您不想要的,请使用更多详细信息编辑您的问题。

awk -v times="10" -v thr="5" '
FNR==1{
  first=$1
  $1=""
  sub(/^ +/,"")
  firstRest1=$1 OFS $2
  thirdField=$3
  $1=$2=$3=""
  sub(/^ +/,"")
  firstRest2=$0
  next
}
{
  val=(val?val ORS:"")$0
}
END{
  ++count
  print first,firstRest1,thirdField,firstRest2 ORS val
  for(i=1;i<=times;i++){
    ++count
    print ++first,firstRest1,thirdField,firstRest2 ORS val
    if(count==(thr)){
      thirdField++
      count=""
    }
  }
}' Input_file | column -t


编辑:由于 OP 要求将整个内容写入(块)的每次迭代都输出到不同的输出文件中,因此添加此解决方案,它将创建输出文件,如output_file1,output_file2等等。

awk -v times="10" -v thr="5" '
FNR==1{
  first=$1
  $1=""
  sub(/^ +/,"")
  firstRest1=$1 OFS $2
  thirdField=$3
  $1=$2=$3=""
  sub(/^ +/,"")
  firstRest2=$0
  next
}
{
  val=(val?val ORS:"")$0
}
END{
  fileCnt=1
  output_file="output_file"fileCnt
  ++count
  print first,firstRest1,thirdField,firstRest2 ORS val > (output_file)
  for(i=1;i<=times;i++){
    ++count
    print ++first,firstRest1,thirdField,firstRest2 ORS val > (output_file)
    if(count==(thr)){
      thirdField++
      fileCnt++
      close(output_file)
      output_file="output_file"fileCnt
      count=""
    }
  }
}' Input_file | column -t

推荐阅读