可以根据第一个字符在输入行中添加一个字符

时间:2016-04-11 01:25:24

标签: linux shell csv sed

对于csv文件中第一列通常为空的数据集,我希望以编程方式在每个不以双引号开头的行中插入另一个逗号。 从下面的示例中,您将看到只有某些行以"开头,而这些行是我想要忽略的行。每隔一行都应该获得额外的,

"1967 Universe",1967,"1,141.0",650.6,73.0,417.5,222.6,119.6,309.8,176.0,390.8,225.0,217.8,130.0
,1968,"1,353.4",694.7,84.3,574.4,234.8,119.2,350.1,182.1,477.3,233.9,291.1,159.5
,1969,"1,322.3",624.8,85.2,612.4,215.8,104.7,317.0,149.9,470.5,215.6,319.0,154.6
,1970,"1,351.5",646.8,88.1,616.7,218.3,93.1,287.4,148.1,502.9,246.5,342.9,159.1
,1971,"1,924.6",906.1,132.9,885.7,303.6,127.3,421.1,208.1,725.4,338.6,474.6,232.1
"1972 Universe",1972,"2,218.9","1,033.1",148.6,"1,037.2",333.3,147.3,440.8,230.1,905.4,391.5,539.3,264.3
,1973,"1,819.5",882.1,117.0,820.5,271.9,141.6,361.4,197.5,763.2,323.9,423.1,219.0
,1974,"1,074.4",643.8,64.4,366.2,165.4,97.2,241.3,154.5,390.1,223.7,277.6,168.4
,1975,939.2,675.5,63.8,199.8,129.5,92.6,241.5,169.3,292.7,222.8,275.5,190.8
,1976,"1,296.2",893.6,93.1,309.5,152.4,111.2,326.1,219.4,401.7,292.6,416.0,270.5
,1977,"1,690.0","1,126.1",121.3,442.7,181.9,126.8,402.4,269.3,561.1,370.1,544.6,359.9
"1978 Universe",1978,"1,800.5","1,182.6",130.6,487.3,194.4,132.9,388.0,260.8,667.6,439.3,550.5,349.6
,1979,"1,551.8",981.5,125.4,444.8,166.9,110.2,289.1,182.4,628.0,392.1,467.7,296.7
,1980,"1,190.6",710.4,114.5,365.7,117.9,75.7,192.0,107.9,561.9,333.0,318.9,193.7
,1981,985.5,564.3,101.8,319.4,109.8,65.7,133.3,78.3,491.1,270.7,251.3,149.5
,1982,"1,000.5",546.4,88.3,365.8,106.7,65.7,126.3,67.6,543.5,281.1,224.1,132.0
,1983,"1,605.2",901.5,133.7,570.1,164.1,112.3,187.8,117.4,862.9,443.0,390.4,228.6

我认为这可以通过sed完成,但我对Regex不熟悉,不知道如何进行条件替换。

我发现的唯一相似的例子是

sed -ri 's/[^,]+/REPLACEMENT/' file.csv

所以它可能看起来像

sed -ri 's/[^,]+/,/' file.csv

但我不认为这是对的

sed 's/\,/\,,/'

几乎可以工作,但它会在逗号的每个第一个实例之后替换逗号,这不是我之后的事。例如:

"2004 Universe",,2004,"2,070.1","1,613.4",90.4,366.2,197.0,131.8,370.5,295.5,960.8,756.1,541.9,430.0
,,2005,"2,155.3","1,682.0",84.0,389.3,203.8,126.6,353.9,278.7,"1,039.0",826.8,558.6,450.0

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

对于肯定问题的表述 - 将,添加到, 开头的所有行 - 请参阅{{3 }}

要将,添加到不以" 开头的所有行,请尝试以下操作:

sed -i -r 's/^[^"]/,&/' file.csv
  • ^[^"]会在行的开头(")捕获不是[^"]^)的任何单个字符,并将其替换为{ {1}},后跟匹配正则表达式(,)的字符串,即该行的第一个字符。 (在您的示例输入中也是&)。

    • 注意,的潜在混淆的明显用法:一方面作为开始分隔符^之后的行首锚,另一方面作为否定运算符括号表达式(字符集)(/)中的字符在另一方面。

    • 请注意,非标准选项[^...]会激活对ERE的支持(扩展正则表达式),而-r默认需要BRE( basic 正则表达式) 上面的工作也没有sed,但如果使用ERE是一个选项,它们更可取,因为它们提供了更多的功能,而且它们的语法更像是其他语言中的正则表达式。

      < / LI>
  • 任何不匹配的行,即 -r开头的任何行,都按原样传递。

至于您尝试的内容

"

在行上匹配一个或多个sed -ri 's/[^,]+/,/' file.csv )个字符而不是+ ,因为括号表达式(字符集){ {1}}不是锚定到字符串的开头(,后面有一个[^,])。

除此之外,您的替换字符串不包含匹配的字符串,因此它将替换匹配^而不是前缀。< / p>

/

再次缺少字符串开头的正则表达式的锚定,因此会替换该行上的第一个,
(顺便说一句,在这种情况下,sed 's/\,/\,,/' 都不需要。)