Grep 文件中一行的第 6 列并将其替换为字符串

问题描述

我有一个 ddl 的文件,如下所示.. 现在以 (如果不存在则创建表 tbl1) 开头的行中的第 6 列是表名.. 我想用 DB.table 名称替换表名。 在具有位置的行中,它应该填充 $tbl 作为表名。下面是示例输入和输出

    Create table if not exists tbl1 (
    col1 int;
    col2 string )
location hdfs://directory/$tbl
    Create table if not exists tbl2 (
    col3 int;
    col2=4 float)
location hdfs://directory/$tbl

替换后输出应该变成如下图

    Create table if not exists DB.tbl1 (
    col1 int;
    col2 string )
location hdfs://directory/tbl1
    Create table if not exists DB.tbl2 (
    col3 int;
    col2=4 float)
location hdfs://directory/tbl2

谁能建议如何实现这一点

解决方法

sed - 用于文本替换的强大 linux 命令。

sed 's/tbl/DB.tbl/' filename - 将 所有 出现的 'tbl' 替换为 'DB.tbl' 并达到想要的结果。 (慎用)。

进一步阅读:https://www.geeksforgeeks.org/sed-command-in-linux-unix-with-examples/

awk 也可能有帮助:

grep "Create" filename | awk '{print $6}' - 将打印文件名中带有“Create”字样的第 6 列行。

祝你好运。