使用分隔符将单行拆分为多行;

使用分隔符将单行拆分为多行;

我需要将单行输出分成多行;作为分隔符。输入由 shell 脚本生成,如下所示:

REVOKE ALL ON XXXXXX_ABC_AAA FROM PUBLIC ; REVOKE ALL ON XBJE_XXXXX_ABC_AAA FROM PUBLIC ; REVOKE ALL ON XBJE_XXADTXXX_ABC_AAA FROM PUBLIC ; REVOKE ALL ON XBJE_XXVXXX_ABECC_AAA FROM PUBLIC ;

我需要将其分成多行,如下所示:

REVOKE ALL ON XXXXXX_ABC_AAA FROM PUBLIC ;
REVOKE ALL ON XBJE_XXXXX_ABC_AAA FROM PUBLIC ;
REVOKE ALL ON XBJE_XXADTXXX_ABC_AAA FROM PUBLIC ;
REVOKE ALL ON XBJE_XXVXXX_ABECC_AAA FROM PUBLIC ;

我怎样才能做到这一点?

答案1

您可以简单地使用sed转换;;\n

$ line="REVOKE ALL ON XXXXXX_ABC_AAA FROM PUBLIC ; REVOKE ALL ON XBJE_XXXXX_ABC_AAA FROM PUBLIC ; REVOKE ALL ON XBJE_XXADTXXX_ABC_AAA FROM PUBLIC ; REVOKE ALL ON XBJE_XXVXXX_ABECC_AAA FROM PUBLIC ;"

$ sed 's/; */;\n/g' <<< "$line"
REVOKE ALL ON XXXXXX_ABC_AAA FROM PUBLIC ;
REVOKE ALL ON XBJE_XXXXX_ABC_AAA FROM PUBLIC ;
REVOKE ALL ON XBJE_XXADTXXX_ABC_AAA FROM PUBLIC ;
REVOKE ALL ON XBJE_XXVXXX_ABECC_AAA FROM PUBLIC ;

因此,如果您的脚本被调用foo.sh,您会这样做:

foo.sh | sed 's/;/;\n/g'

答案2

使用tr及标准sed

$ tr -s ';' '\n' <file | sed -e 's/^[[:blank:]]*//' -e 's/$/;/'
REVOKE ALL ON XXXXXX_ABC_AAA FROM PUBLIC ;
REVOKE ALL ON XBJE_XXXXX_ABC_AAA FROM PUBLIC ;
REVOKE ALL ON XBJE_XXADTXXX_ABC_AAA FROM PUBLIC ;
REVOKE ALL ON XBJE_XXVXXX_ABECC_AAA FROM PUBLIC ;

这将首先用换行符替换所有分号,然后修剪掉每个生成行开头的所有空格,并在末尾添加一个分号。

如果您的输入存储在 abashzshshell 变量中,请使用

printf '%s;\n' "${var//;/;$'\n'}" | sed 's/^[[:blank:]]*//'

这将首先;用相同的字符替换所有内容,然后是文字换行符。然后它会修剪掉每条生成行开头的空格。

相关内容