如何在shell scipt中处理典型的数组?

时间:2015-10-06 06:01:06

标签: shell awk

我有变量“a”,其中包含错误我希望将其视为数组并用newlines分隔。如何使用shell脚本或awk转换为单行?

输入数据

a=(BEGIN DE_DUP_DROP_DY_TABLE1('$Table_Name'); END;
Error at line 1
ORA-06550: line 1, column 7:
PLS-00201: identifier 'DE_DUP_DROP_DY_TABLE1' must be declared
ORA-06550: line 1, column 7:
PL/SQL: Statement ignored)

预期产出

BEGIN DE_DUP_DROP_DY_TABLE1('$Table_Name'); END; | Error at line 1 | ORA-06550: line 1, column 7: | PLS-00201: identifier 'DE_DUP_DROP_DY_TABLE1' must be declared |ORA-06550: line 1, column 7: | PL/SQL: Statement ignored

1 个答案:

答案 0 :(得分:1)

假设:

a="BEGIN DE_DUP_DROP_DY_TABLE1('$Table_Name'); END;
Error at line 1
ORA-06550: line 1, column 7:
PLS-00201: identifier 'DE_DUP_DROP_DY_TABLE1' must be declared
ORA-06550: line 1, column 7:
PL/SQL: Statement ignored"

您可以使用以下方式生成一行输出:

echo "$a" | tr '\n' '|' | sed 's/|/ | /g'

产量:

BEGIN DE_DUP_DROP_DY_TABLE1(''); END; | Error at line 1 | ORA-06550: line 1, column 7: | PLS-00201: identifier 'DE_DUP_DROP_DY_TABLE1' must be declared | ORA-06550: line 1, column 7: | PL/SQL: Statement ignored | 

如果您需要删除最终的|(它来自echo输出末尾的换行符),请将其删除:

$ echo "$a" | tr '\n' '|' | sed -e 's/|/ | /g' -e 's/ | $//'
BEGIN DE_DUP_DROP_DY_TABLE1(''); END; | Error at line 1 | ORA-06550: line 1, column 7: | PLS-00201: identifier 'DE_DUP_DROP_DY_TABLE1' must be declared | ORA-06550: line 1, column 7: | PL/SQL: Statement ignored
$

或者不要生成它:

$ printf "%s" "$a" | tr '\n' '|' | sed 's/|/ | /g'
BEGIN DE_DUP_DROP_DY_TABLE1(''); END; | Error at line 1 | ORA-06550: line 1, column 7: | PLS-00201: identifier 'DE_DUP_DROP_DY_TABLE1' must be declared | ORA-06550: line 1, column 7: | PL/SQL: Statement ignored
$

当然,这些输出非常一致,并在每个管道周围放置一个空格(与样本输出不同)。如果数据中有管道,则会出现问题(管道周围出现意外/不需要的空间)。

如果,你有一个数组,每行都有一个单独的元素,你可以调整上面的代码来简单地处理它(使用printf):

$ a=("BEGIN DE_DUP_DROP_DY_TABLE1('$Table_Name'); END;"
"Error at line 1"
"ORA-06550: line 1, column 7:"
"PLS-00201: identifier 'DE_DUP_DROP_DY_TABLE1' must be declared"
"ORA-06550: line 1, column 7:"
"PL/SQL: Statement ignored")
$ printf "%s\n" "${a[@]}" | tr '\n' '|' | sed -e 's/|/ | /g' -e 's/ | $//'
BEGIN DE_DUP_DROP_DY_TABLE1(''); END; | Error at line 1 | ORA-06550: line 1, column 7: | PLS-00201: identifier 'DE_DUP_DROP_DY_TABLE1' must be declared | ORA-06550: line 1, column 7: | PL/SQL: Statement ignored
$