gpt4 book ai didi

linux - 如何使用AWK从文件连续输出行

转载 作者:行者123 更新时间:2023-12-03 09:55:46 24 4
gpt4 key购买 nike

我有一个包含多行的文件,并且我想连续输出文件的某些行,例如第一次,从第1行打印到第5行,下次,从第2行打印到第6行,依此类推。
我发现AWK是一个非常有用的功能,我尝试自己编写代码,但是它什么也没输出。
以下是我的代码

#!/bin/bash
for n in `seq 1 3`
do
N1=$n
N2=$((n+4))
awk -v n1="$N1" -v n2="$N2" 'NR == n1, NR == n2 {print $0}' my_file >> new_file
done
例如,我有一个名为my_file的输入文件
1 99 tut
2 24 bcc
3 32 los
4 33 rts
5 642 pac
6 23 caas
7 231 cdos
8 1 caee
9 78 cdsa
然后我期望输出文件为
1 99 tut
2 24 bcc
3 32 los
4 33 rts
5 642 pac
2 24 bcc
3 32 los
4 33 rts
5 642 pac
6 23 caas
3 32 los
4 33 rts
5 642 pac
6 23 caas
7 231 cdos

最佳答案

您能否请尝试按照GNU awk中显示的示例进行后续操作,编写和测试。如果需要提及所有需要在lines_from变量中打印的行,则有一个名为till_lines的变量,它告诉我们从特定行需要打印多少行(例如->从第一行开始也打印接下来的4行) )。另外,我已经测试了OP的代码,它对我来说很好用,因为它使用new_file生成输出文件,因为在bash循环中调用awk并不是一个好习惯,因此在这里也进行了改进。

awk -v lines_from="1,2,3" -v till_lines="4" '
BEGIN{
num=split(lines_from,arr,",")
for(i=1;i<=num;i++){ line[arr[i]] }
}
FNR==NR{
value[FNR]=$0
next
}
(FNR in line){
print value[FNR] > "output_file"
j=""
while(++j<=till_lines){ print value[FNR+j] > "output_file" }
}
' Input_file Input_file
当我看到 output_file的内容时,我可以看到以下内容:
cat output_file
1 99 tut
2 24 bcc
3 32 los
4 33 rts
5 642 pac
2 24 bcc
3 32 los
4 33 rts
5 642 pac
6 23 caas
3 32 los
4 33 rts
5 642 pac
6 23 caas
7 231 cdos
说明:添加以上详细说明。
awk -v lines_from="1,2,3" -v till_lines="4" '    ##Starting awk program from here and creating 2 variables lines_from and till_lines here, where lines_from will have all line numbers which one wants to print from. till_lines is the value till lines one has to print.
BEGIN{ ##Starting BEGIN section of this program from here.
num=split(lines_from,arr,",") ##Splitting lines_from into arr with delimiter of , here.
for(i=1;i<=num;i++){ ##Running a for loop from i=1 to till value of num here.
line[arr[i]] ##Creating array line with index of value of array arr with index of i here.
}
}
FNR==NR{ ##Checking condition FNR==NR which will be TRUE when 1st time Input_file is being read.
value[FNR]=$0 ##Creating value with index as FNR and its value is current line.
next ##next will skip all further statements from here.
}
(FNR in line){ ##Checking condition if current line number is coming in array then do following.
print value[FNR] > "output_file" ##Printing value with index of FNR into output_file
j="" ##Nullifying value of j here.
while(++j<=till_lines){ ##Running while loop from j=1 to till value of till_lines here.
print value[FNR+j] > "output_file" ##Printing value of array value with index of FNR+j and print output into output_file
}
}
' Input_file Input_file ##Mentioning Input_file names here.

关于linux - 如何使用AWK从文件连续输出行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63895366/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com