dex*_*x10 3 bash awk while-loop
所以基本上我有一个包含很多空行的文本文件。我们将其命名为 time.txt,该文件的一部分如下所示:
1 5 20
2 5 12
1 6 3
2 6 4
1 10 30
2 10 21
1 11 27
2 12 8
1 11 34
2 12 20
1 10 30
2 10 21
Run Code Online (Sandbox Code Playgroud)
现在,我有另一个名为location.txt 的文件,它包含的行数与time.txt 中的空行数相同。它看起来像这样:
110 -7 5.000 66
110 -7 5.000 99
110 -7 5.000 60
Run Code Online (Sandbox Code Playgroud)
而我要的其实很简单:我只是想填补空白行TIME.TXT,每行location.txt,给预期的结果:
110 -7 5.000 66
1 5 20
2 5 12
1 6 3
2 6 4
110 -7 5.000 99
1 10 30
2 10 21
1 11 27
2 12 8
1 11 34
2 12 20
110 -7 5.000 60
1 10 30
2 10 21
Run Code Online (Sandbox Code Playgroud)
我解决这个问题的方法是逐行读取location.txt,将每一行存储在循环内的变量中,然后使用 awk 检测time.txt 中的空行并将其替换为存储的循环变量。我的代码如下所示:
time="time.txt"
location="location.txt"
while read -r lines_locs; do
awk '!NF{$0=$lines_locs}1' $time
done < "$location"
Run Code Online (Sandbox Code Playgroud)
但这只会在我的屏幕中打印出time.txt而没有进行替换。另外,与预期的行数相比,我打印了太多行。我确定我遗漏了一些东西,如果有人能指出这一点,我会很高兴。
一个在 awk 中使用getline:
$ awk -v file="$location" 'NF==0{if((getline < file)<=0)$0=""}1' "$time"
Run Code Online (Sandbox Code Playgroud)
解释:
$ awk -v file="$location" ' # location file as parameter
NF==0 { # NF==0 considers bare space records empty
if((getline < file)<=0) # when empty read from another file. if failure
$0="" # reset the record. see comments for discussion
}1' "$time" # output
Run Code Online (Sandbox Code Playgroud)
输出:
110 -7 5.000 66
1 5 20
2 5 12
1 6 3
2 6 4
110 -7 5.000 99
1 10 30
2 10 21
1 11 27
2 12 8
1 11 34
2 12 20
110 -7 5.000 60
1 10 30
2 10 21
Run Code Online (Sandbox Code Playgroud)
如果文件location用完记录,脚本将打印空记录。相关讨论见评论。