你好,我在bash中有点丢失,我想向每行添加引号,以便我可以在sql
中使用它们例如,输入文件:
one
two
three
或
one, two, three
将返回为:
'one', 'two', 'three'
哪些命令是最佳解决方案?
假设其中一个字符串中没有单个引号或空格,您可以使用for
循环进行此操作:
for word in $(<infile); do echo -n "'$word', "; done | sed -e 's/, $//'
eg:
> 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/, $//'
在一行情况下
kent$ echo "one, two, three"|awk -v q="'" '{$0=q $0 q; gsub(/, */, q", "q)}7'
'one', 'two', 'three'
在Multilines Case
中kent$ echo "one
two
three"|awk -v q="'" -v RS="" '{$0=q $0 q;gsub(/n/,q", "q)}7'
'one', 'two', 'three'
使用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'
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'