在文件的每个字符串中引用

时间:2014-01-24 10:39:52

标签: bash scripting quotes

您好我在bash中有点迷失,我想在每行添加引号,以便我可以在SQL中使用它们

例如输入文件:

one
two
three

one, two, three

将以:

返回
'one', 'two', 'three'

哪个命令对此最好的解决方案?

4 个答案:

答案 0 :(得分:0)

使用gnu-awk可以:

> cat file
one, two, three
foo
bar
baz

> awk -v q="'" '{$0=q $0 q}1' RS=' *[,\n] *' file
'one'
'two'
'three'
'foo'
'bar'
'baz'

答案 1 :(得分:0)

假设所有字符串都没有单引号或空格,您可以使用for循环执行此操作:

for word in $(<infile); do echo -n "'$word', "; done | sed -e 's/, $//'

例如:

> cat infile
one
two
three

> for word in $(<infile);  do echo -n "'$word', "; done | sed -e 's/, $//'
'one', 'two', 'three'

易于阅读:

for word in $(<infile)
do
    echo -n "'$word', "
done | sed -e 's/, $//'

答案 2 :(得分:0)

在单行案例中

kent$  echo "one, two, three"|awk -v q="'" '{$0=q $0 q; gsub(/, */, q", "q)}7'
'one', 'two', 'three'
多线情况下的

kent$  echo "one
two
three"|awk -v q="'" -v RS="" '{$0=q $0 q;gsub(/\n/,q", "q)}7'
'one', 'two', 'three'

答案 3 :(得分:0)

ruby -rcsv -ne '
    BEGIN {attributes = {:col_sep=>", ", :quote_char=>"'\''", :force_quotes=>true}}
    CSV.parse($_) {|row| puts CSV.generate_line(row.map {|e| e.strip}, attributes)}
' <<END
one, two, three
four
five, six
END
'one', 'two', 'three'
'four'
'five', 'six'