用CSV特定列中的空字符串替换连字符

时间:2018-11-20 10:23:41

标签: shell

我有一个30列的csv文件。我只需要从第30列中删除连字符(第3和第4列中包含连字符,但不应将其删除。)我在awk命令下面尝试实现此功能。但这正在删除一些记录,我找不到原因。

lazy var sections : Array<Section> = {

    guard let path = Bundle.main.path(forResource: "myFile", ofType: "json") else { return [] }
    let url = URL(fileURLWithPath: path)

    guard let data = try? Data(contentsOf: url) else { return [] }

    do {
        let decoder = JSONDecoder()
        decoder.dateDecodingStrategy = .secondsSince1970
        let sections = try decoder.decode(Array<Section>.self, from: data)
        return sections
    } catch {
        print(error)
    }
    return []
}()

请提出一种在不删除记录的情况下删除csv特定列中的连字符的解决方案。

PFB示例输入:

awk -f=',' 'gsub= "\\-","",$30)' OFS=, input.csv > output.csv

预期输出:

roll,name,type
01,j-man,re-open
01,i-man,reopen
01,j-man,reopen
01,r-man,re-open

1 个答案:

答案 0 :(得分:0)

我用第10列的示例进行了说明。您的案例将10替换为30

$ cat > hyphen.txt
roll,name,type,col4,col5,col6,col7,col8,col9,col10,col11
01-1,j-man,re-open,r4,r5,r6,r7,r8,r9,ab--cd,r11
01-2,i-man,reopen,r4,r5,r6,r7,r8,r9,pq--rs,r11
01-3,j-man,reopen,r4,r5,r6,r7,r8,r9,r10,r11
01-4,r-man,re-open,r4,r5,r6,r7,r8,r9,r10,r11


$ awk -F"," ' { gsub(/[-]/,"",$10); print } ' hyphen.txt
roll,name,type,col4,col5,col6,col7,col8,col9,col10,col11
01-1 j-man re-open r4 r5 r6 r7 r8 r9 abcd r11
01-2 i-man reopen r4 r5 r6 r7 r8 r9 pqrs r11
01-3,j-man,reopen,r4,r5,r6,r7,r8,r9,r10,r11
01-4,r-man,re-open,r4,r5,r6,r7,r8,r9,r10,r11