如何从文本文件中删除方括号和逗号?

时间:2019-04-30 23:49:36

标签: bash

我有一个从Spark SQL查询写入的文本文件。它被编写为文本文件,方括号内用逗号分隔,如下所示。我需要删除括号和逗号。到目前为止,我已经拥有sed -e 's/]//g' -e 's/,//g' $ filename了,但这只是删除了后括号和所有逗号。

[371590146, ,2019-04-28, ,123.2]
[371712941, ,2019-04-29, ,128.72]
[371828179, ,2019-04-30, ,148.35]

3 个答案:

答案 0 :(得分:2)

尝试:

$ sed -e 's/\[//g' -e 's/\]//g' -e 's/,//g' file
371590146 2019-04-28 123.2
371712941 2019-04-29 128.72
371828179 2019-04-30 148.35

或:

$ sed -e 's/[][,]//g' file
371590146 2019-04-28 123.2
371712941 2019-04-29 128.72
371828179 2019-04-30 148.35

或:

$ sed -Ee 's/\[|\]|,//g' file
371590146 2019-04-28 123.2
371712941 2019-04-29 128.72
371828179 2019-04-30 148.35

请注意,[]是正则表达式有效字符。如果希望将它们从字面上看做方括号,则应使用\将其转义。 (有时候,一个程序足够聪明,知道它是字面上的意思,就像问题中的代码一样,但最好的做法是不要指望它。)

[][,]表示][,中的任何一个。 [...]被称为括号表达式。它与方括号中包含的任何字符匹配。

\[|\]|,也表示][,中的任何一个。在扩展的正则表达式中(-E选项),字符|分隔分支。如果|两侧的正则表达式匹配,则此匹配。

答案 1 :(得分:2)

    public static int [][] forceRandom(int [] [] parray){
    int i, j;
    for(i = 0; i < parray.length; i++){
        for(j = 0; j<parray[i].length; j++){
            if(parray[i][j] == parray[i][j]){
                int temp = parray[i][j];
                parray[i][j] = parray[temp][j+1];
            }
        }
    }

    return parray;

} ` 

输出:

371590146 2019-04-28 123.2
371712941 2019-04-29 128.72
371828179 2019-04-30 148.35

请参阅:tr -d '[],' <file

答案 2 :(得分:1)

仅仅是因为我喜欢添加替代方法(Cyrus的答案比John1024的答案要好得多),所以这是一种全速解决方案,虽然速度慢很多,但也可以用。

while IFS=",][ " read -a f
do echo ${f[@]} # proper quotes add an extra space before each field
done < file