【问题标题】:text file manipulations using shell script使用 shell 脚本操作文本文件
【发布时间】:2021-02-13 21:05:12
【问题描述】:

我已将输入数据保存在文本文件(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

【问题讨论】:

  • 发布“预期输出”然后说“在那之后......”然后发布其他输出令人困惑。你想要两组数据输出吗?如果是这样,他们应该去单独的文件还是什么?请edit您的问题以澄清您的要求和示例,特别是因为它与拥有 2 组单独的预期输出有关。

标签: linux shell for-loop awk


【解决方案1】:

您的问题不是很清楚,此解决方案仅完全基于您显示的预期示例输出。解决方案有 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_file1output_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

【讨论】: