查找文件的行模式,打印行直到第一个空行



我有一个包含数据头的文件,另一个包含所有头的更多信息。所以,我首先需要逐行读取头文件,然后在另一个文件中查找该行,如果找到了模式,则复制该行和下一行,直到新文件中的第一个空行。

我一直在尝试这个:

#!/bin/bash
fname1= header.txt
fname2= complete-data.txt
cat $fname1 | while read -r line; do
echo $line
sed -n "$line/,/^ *$/p" $fname2 > new-file.txt
done

但它不起作用:

sed: can't read line/,/^ *$/p: No such file or directory

当我复制一行并手动操作时,它会起作用:

sed -n 'line_to_find/,/^ *$/p2' complete-data.txt > new-file.txt

帮助

欢迎使用SO.

首先,在模式的开头添加一个/

其次,在每次迭代中都要覆盖输出
在循环结束时进行I/O控制:

$: cat header.txt
2    
4
$: cat complete-data.txt
1
this is #1
just #1
2
this is #2
just #2
3
this is #3
just #3
4
this is #4
just #4
5
this is #5
just #5
$: while read -r line
do sed -n "/$line/,/^ *$/p" complete-data.txt
done < header.txt > new-file.txt
$: cat new-file.txt
2
this is #2
just #2
4
this is #4
just #4

自从我写了这个问题后,我意识到我错过了/。但是,钢铁不起作用!!我以为可能是空间问题,但我已经解决了这个问题,但它仍然不起作用。。。

这是我的真实案例:

header.txt

2019  11 16 46   6.4183 -29.23337  -71.06854   5.0000 NOEVID          0.116     5.612   4.0   5.0  20.0  21.0   9   7  16

完整数据.txt

2019  11  2 48  45.5745 -29.14132  -71.05508  54.6150 NOEVID          0.215     5.799   8.0  12.0  19.0  23.9   6   6  12
- CP50  2019  11  2 48  57.169 P           0.601      0.588 
- CP50  2019  11  2 49   5.164 S           1.472      0.354 
- CP51  2019  11  2 48  55.744 P           0.254     -0.044 
- CP51  2019  11  2 49   3.199 S           0.910     -0.250
2019  11 16 46   6.4183 -29.23337  -71.06854   5.0000 NOEVID          0.116     5.612   4.0   5.0  20.0  21.0   9   7  16
- CP50  2019  11 16 46  16.120 P           0.351      0.097  
- CP51  2019  11 16 46  15.205 P           0.247     -0.099  
- CP52  2019  11 16 46  16.950 P           0.382      0.104
2019  12  0 45  30.5744 -29.01455  -71.32178  37.2900 NOEVID          0.093     6.448   7.0   5.0  12.0  14.8  10  10  20
- C59B  2019  12  0 45  58.219XS           4.500      0.098 
- CP02  2019  12  0 45  54.504*P           0.691      2.203 
- CP02  2019  12  0 46   7.929 S           1.412     -0.563

我的脚本:

input="header.txt"
while IFS= read line 
do
j=$(printf "%sn" "$line")
echo "$j"
sed -n "/$j/,/^ *$/p" complete-data.txt >> new-file.txt
done < "$input"

当我运行这个脚本时,new-file.txt是空的。我试着更改最后一行:

done < "$input" > new-file.txt

但是输出文件仍然是空的

但是!如果我手动运行它:

sed -n "/2019  11 16 46   6.4183 -29.23337  -71.06854   5.0000 NOEVID          0.116     5.612   4.0   5.0  20.0  21.0   9   7  16/,/^ *$/p" complete-data.txt >> new-file.txt

这很管用!!

相关内容

最新更新