简体   繁体   English

使用 sed 或 awk 替换匹配后的所有行

[英]Replace all lines after a match using sed or awk

I have the following txt file:我有以下 txt 文件:

Col1,,Col2,,Col 3,,Session,,Time
Mike,,Rg,,Tx,,32658723,,2:00
,,,,,,,,
,,,,,,23623623,,
,,,,,,,,
Joe,,Tx,,Rg,,47235623,,1:00
,,,,,,,,
Peter,,Un,,Xs,,6523,,1:00
,,,,,,,,
Nick,,Xe,,Lk,,67286734,,3:00
,,,,,,,,
,,,,,,,,
,,,,,,32623,,
,,,,,,,,
Bob Li,,Yh,,Xa,,2362,,3:00
,,,,,,,,
,,,,,,,,
,,,,,,,,
,,,,,,,,
,,,,,,323,,
,,,,,,,,
,,,,,,,,
,,,,,,,,
,,,,,,,,
Lin Xu,,Rw,,NB,,1352362,,1:00
,,,,,,,,

The most important value on this file is what is on column 7th.此文件中最重要的值是第 7 列中的内容。 I would like to fill all the empty lines right below the first line which has a value for column 7th.我想填充第一行正下方的所有空行,该行的第 7 列具有值。 Leaving that value untouched.保持该值不变。

I have been trying some send commands like:我一直在尝试一些发送命令,例如:

sed -n '/^,/{g;};h;p'

But it is replacing all the empty lines, even if they do have an expected value.但它正在替换所有空行,即使它们确实具有预期值。

What I would like the above file is to become like this:我希望上面的文件变成这样:

Col1,,Col2,,Col 3,,Session,,Time
Mike,,Rg,,Tx,,32658723,,2:00
Mike,,Rg,,Tx,,32658723,,2:00
Mike,,Rg,,Tx,,23623623,,2:00
Mike,,Rg,,Tx,,23623623,,2:00
Joe,,Tx,,Rg,,47235623,,1:00
Joe,,Tx,,Rg,,47235623,,1:00
Peter,,Un,,Xs,,6523,,1:00
Peter,,Un,,Xs,,6523,,1:00
Nick,,Xe,,Lk,,67286734,,3:00
Nick,,Xe,,Lk,,67286734,,3:00
Nick,,Xe,,Lk,,67286734,,3:00
Nick,,Xe,,Lk,,32623,,3:00
Nick,,Xe,,Lk,,32623,,3:00
Bob Li,,Yh,,Xa,,2362,,3:00
Bob Li,,Yh,,Xa,,2362,,3:00
Bob Li,,Yh,,Xa,,323,,3:00
Bob Li,,Yh,,Xa,,323,,3:00
Bob Li,,Yh,,Xa,,323,,3:00
Bob Li,,Yh,,Xa,,323,,3:00
Bob Li,,Yh,,Xa,,323,,3:00
Lin Xu,,Rw,,NB,,1352362,,1:00
Lin Xu,,Rw,,NB,,1352362,,1:00

This might work for you (GNU sed):这可能对你有用(GNU sed):

sed -E '1b
        /^,{8}$/{g;b}
        /^,{6}\S+,,$/{G;s/^,{6}(\S+),,\n(([^,]*,){6})[^,]*/\2\1/}
        h' file

Ignore the header line.忽略 header 行。

If the line contains empty fields, replace it by the previous good line and break.如果该行包含空字段,则将其替换为上一个好的行并中断。

If the line contains all empty fields bar the seventh, append the last good line and replace its seventh field by that of the current lines.如果该行包含除第七行之外的所有空字段,则 append 是最后一行,并将其第七行替换为当前行的第七行。

This line is now good, make a copy.这条线现在好了,复制一份。

All lines are printed by default.默认打印所有行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM