linux - 使用 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
解决方案
你的问题不是很清楚,这个解决方案完全基于你显示的预期样本输出。解决方案有 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
推荐阅读
- firebase - Square 和 Firebase 之间有集成吗?
- ios - 如何防止得到
从 NSUserDefaults 检索一个对象 - c# - Net Core Web API 2.2 保护敏感数据
- sql - SQL + Powershell:当WHERE匹配时选择语句对匹配的行中的列执行更新
- c# - 我的请求在 HTTPClient 和 RestSharp 中不起作用,但在 Postman 中却很好
- django - 同一个表但不同列的多个外键获取models.object
- c++ - C++ 编译器为什么/如何理解类实例的这种初始化?
- sql-server - 使用 Row_number() 和 Partition,然后排序 desc,并在 DB2 中选择顶部结果
- android - 如何使用 AnimatedVectorDrawables 为渐变设置动画?
- r - 将 ggsave 中的画布大小设置为固定宽度,同时保持绘图的纵横比