我有一个csv文件,其中包括:
# Director, Movie Title, Year, Comment
Ethan Coen, No Country for Old Men, 2007, none
Ethan Coen, "O Brother, Where Art Thou?", 2000, none
Ethan Coen, The Big Lebowski, 1998, "uncredited (with his brother, Joel)"我希望将字段分隔符从",“更改为”区“,但如果逗号位于引号中,则不想更改:因此结果应该如下所示:
# Director| Movie Title| Year| Comment
Ethan Coen| No Country for Old Men| 2007| none
Ethan Coen| "O Brother, Where Art Thou?"| 2000| none
Ethan Coen| The Big Lebowski| 1998| "uncredited (with his brother, Joel)"我尝试过这样做,但得到的输出是: sed -e‘s/(“.”)/|\1 \2/g’
这就是我目前所得到的结果。
伊森·科恩,“哦,兄弟,你在哪里?",2000年,没有
伊森·科恩,“大莱博夫斯基”,1998年,“没有信誉(和他的兄弟乔尔一起)”
发布于 2020-01-17 15:20:43
方法:更改\r中引用的逗号,替换其余逗号,并将\r更改回。第一次尝试适用于给定的输入,但仍然是错误的:
# Wrong
sed -E 's/("[^,]*),([\"]*)/\1\r\2/g; s/,/|/g;s/\r/,/g' file它在一个字段中有两个逗号的行上失败。
应重复第一次替换,直到替换所有引号为止:
sed -E ':a;s/("[^,"]*),([^"]*)"/\1\r\2"/g; ta; s/,/|/g;s/\r/,/g' file发布于 2020-01-17 17:25:55
这可能对您有用(GNU sed):
sed -E 's#"[^"]*"#$(echo &|sed "y/,/\\n/;s/.*/\\\"\&\\\"/")#g;s/.*/echo "&"/e;y/,\n/|,/' file这种替换将,的双引号转换为换行符,然后将,的转换为|的,\n的转换为,的。
https://stackoverflow.com/questions/59788049
复制相似问题