regex - Unix : Find and replace consecutive commas to consecutive pipelines

标签 regex linux unix awk sed

我正在将双引号 CSV 转换为 Unix 中的管道分隔 txt 文件。 我使用以下 sed 命令将“,”替换为 |然后删除开始和结束双引号。

sed -e 's/","/|/g' -e 's/"//g' filenm.csv > filenm.txt

但文件似乎有连续的逗号,没有双引号,而且它们没有被替换。

Col1|col2|col3|col4|col5|col6|col7|col8
Val1|val2|val3,,,,val7|val8

现在我想将所有这些连续的逗号转换为连续的管道,因为它们表示空字段或空字段。

其他字段在字段值内也有逗号,不应更改。

我尝试使用下面的方法,但没有用。

sed -e 's/,{1,\}/|{1,\}/g' filenm.csv > filenm.txt

在记事本中打开的示例 csv 文件:

"ID","Name","DOB","Age","Address","City","State","Country","Phone number"
"123","ABC","12/20/2020","15","No.38,3rd st, RRR NNN, TRT",,,,"9999999999"
"456","DEF","12/20/2020",,,,,"test-country","9999999999"
"465","XYZ",,,"No.38,3rd st, RRR NNN, TRT",,,,"9999999999"

我希望这有助于重现和解决问题。

提前致谢....

最佳答案

这可能对你有用(GNU sed):

sed -E ':a;s/^(("[^",]*",+)*"[^",]*),/\1\n/;ta;y/,\n/|,/' file

用换行符迭代替换 , 之间的 ",然后将 , 翻译为 |的和 , 的换行符。

关于regex - Unix : Find and replace consecutive commas to consecutive pipelines,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65629969/

相关文章:

PHP (Regex) 检查字符串是否至少包含 4 位数字 + 2 个字母

linux - unix中父进程是什么意思

c - 如何将后台进程移动到前台

php - preg_match 只有 4 位数字

JavaScript 字符串 : get content of two standing next to each other pieces of content and wrap them together

javascript - 匹配尚未引用的标识符

php - 将多行linux发送到PHP exec()

linux - Tcsh 脚本不退出

linux - 比 pthread_self 或 gettid 更好的获取线程 ID 的方法

linux - bash 脚本 : how to get item name on a radiolist using dialog