如何用AWK中的CSV填充空单元格?

时间:2017-03-20 18:34:16

标签: bash csv awk

我有一个像这样的CSV文件,<string>作为分隔符:

@

第一列包含章节编号。第二列包含该章的文本。

我需要填写A列中的所有章节编号,以便下面的任何空单元格都填充章节编号。例如,输出将是:

Chapter 1@This is some text.
        @This is some more text.
        @This is yet some more text.
Chapter 2@This is some text.
        @This is some more text.
        @This is yet some more text.

如何填写表格A列中的所有空单元格?

3 个答案:

答案 0 :(得分:3)

您可以像这样使用awk

awk  'BEGIN{FS=OFS="@"} {if ($1 ~ /^[ \t]*$/) $1=ch; else ch=$1} 1' file

Chapter 1@This is some text.
Chapter 1@This is some more text.
Chapter 1@This is yet some more text.
Chapter 2@This is some text.
Chapter 2@This is some more text.
Chapter 2@This is yet some more text.

使用简单的正则表达式检查,我们验证$1是否为空 - 然后我们设置变量ch as name of the first chapter. Then in next subsequent lines we set chapter name to the value we've stored in variable ch`。

答案 1 :(得分:1)

使用awk

的其他方式

<强>输入

$ cat file
Chapter 1@This is some text.
        @This is some more text.
        @This is yet some more text.
Chapter 2@This is some text.
        @This is some more text.
        @This is yet some more text.

<强>输出

$ awk 'BEGIN{FS=OFS="@"}/^[ \t]+/{$1=c}{c=$1}1' file
Chapter 1@This is some text.
Chapter 1@This is some more text.
Chapter 1@This is yet some more text.
Chapter 2@This is some text.
Chapter 2@This is some more text.
Chapter 2@This is yet some more text.

$ awk 'BEGIN{FS=OFS="@"}/^[^\t ]+/{c=$1}{$1=c}1' file
Chapter 1@This is some text.
Chapter 1@This is some more text.
Chapter 1@This is yet some more text.
Chapter 2@This is some text.
Chapter 2@This is some more text.
Chapter 2@This is yet some more text.

答案 2 :(得分:1)

试试这个解决方案 -

awk -F@  '$1!~/^[[:space:]]+/ {h=$1FS} {print ($1!~/^[[:space:]]+/? $0 : h$2)}' f
Chapter 1@This is some text.
Chapter 1@This is some more text.
Chapter 1@This is yet some more text.
Chapter 2@This is some text.
Chapter 2@This is some more text.
Chapter 2@This is yet some more text.