答案1
使用sed
:
sed "s/.*/'&','&'/" filename
s/foo/bar
替换foo
为bar
..*
匹配整行,&
在替换部分插入整个匹配。
答案2
你已经得到sed
答案了。以下是一些替代方案:
awk
:将单引号设置为变量q
(为了便于阅读)并将out
其设置为单引号括起来的记录,然后out
以所需的格式打印:
awk -v q="'" '{out=q$0q; print out","out}'
bash
:读取每一行,设置变量out
以包含单引号括起来的行,最后以所需格式打印:
while IFS= read -r line; do out="'$line'"; printf '%s,%s\n' "$out" "$out"; done
python
:读取每一行,并使用函数以所需的格式打印print()
:
#!/usr/bin/env python3
with open('file.txt') as f:
for line in f:
line = line.rstrip()
print("'{}','{}'".format(line, line))
perl
.*
:用适当的格式替换每一行( ),$&
替换代表匹配的部分,在本例中为整行:
perl -pe "s/.*/'$&','$&'/"
例子:
% cat file.txt
abc
xyz
pqr
mno
% awk -v q="'" '{out=q$0q; print out","out}' file.txt
'abc','abc'
'xyz','xyz'
'pqr','pqr'
'mno','mno'
% while IFS= read -r line; do out="'$line'"; printf '%s,%s\n' "$out" "$out"; done <file.txt
'abc','abc'
'xyz','xyz'
'pqr','pqr'
'mno','mno'
% perl -pe "s/.*/'$&','$&'/" file.txt
'abc','abc'
'xyz','xyz'
'pqr','pqr'
'mno','mno'