python或bash-添加";在行的开头和“;,行尾

python或bash-添加";在行的开头和“;,行尾,python,linux,bash,Python,Linux,Bash,我有一个类似这样的文本文件 first line line nr 2 line three 等 我想产生 "first line", "line nr 2", "line three", 我想知道如何在python或bash中实现这一点,如果它更容易/更快的话。我知道在python(?)中,打开文件和只读取一行代码是不同的,但我不确定在这种情况下使用哪个选项,更重要的是,如何添加这些字符。任何建议都会有帮助。有很多简单的方法 一个简单的perl oneliner: perl -pi -e '

我有一个类似这样的文本文件

first line
line nr 2
line three

我想产生

"first line",
"line nr 2",
"line three",

我想知道如何在python或bash中实现这一点,如果它更容易/更快的话。我知道在python(?)中,打开文件和只读取一行代码是不同的,但我不确定在这种情况下使用哪个选项,更重要的是,如何添加这些字符。任何建议都会有帮助。

有很多简单的方法

一个简单的perl oneliner:

perl -pi -e 's/^(.*)$/\"$1\",/g' /path/to/your/file

为了解释一点,正则表达式
^(.*)$
获取行开始(
^
)和行结束(
$
)之间的所有内容(
(.*)
),然后使用
$1
匹配组变量用引号和逗号重新构造它。

作为参考,以防有人想用python做同样的事情。有一个方便的模块可以这样使用:

import fileinput
import sys, os

for line in fileinput.input(inplace=True):
    sys.stdout.write('"%s",%s' % (line.rstrip(os.linesep), os.linesep))
然后将其作为脚本运行:

python myscript.py file1 file2 file3

这将为您更改现有文件。

成为真正的unix极客:使用sed

sed 's/^/"/; s/$/",/;' < your_text_file
sed的/^/“/;s/$/”,/;”<您的\u文本\u文件
如果要用反斜杠转义现有的双引号,请使用
的/“/\\”/g;s/^/“/;s/$/”,/;'作为模式


非常适合这种类型的任务。看看一个可笑的长镜头。

sh+awk在这里也不错

!/bin/sh
for FILE in "$@"
do
   awk '{print "\" $0 "\","}' < $FILE > $FILE.tmp
   mv $FILE.tmp $FILE
done
/垃圾箱/垃圾箱
对于“$@”中的文件
做
awk'{print“\”$0“\”,“}”<$FILE>$FILE.tmp
mv$FILE.tmp$FILE
完成
在Bash中:

while read line
    do
    echo "\"${line}\","
done < inputfile
读取行时
做
回显“\”${line}\”,“
完成<输入文件

此任务不需要构造正则表达式(带反向引用)。这是一个昂贵的操作,因为您不打算更改行中的内容。最简单的方法就是将它们打印出来

    awk '{print "\042"$0"\042,"}' file 
对大文件执行操作的结果:

$ head -5 file
this is line
this is line
this is line
this is line
this is line
$ wc -l < file
9545088

$ time  awk '{print "\042"$0"\042,"}' file  >/dev/null

real    0m15.574s
user    0m15.327s
sys     0m0.172s

$ time sed 's/.*/"&",/' file > /dev/null

real    0m31.717s
user    0m31.465s
sys     0m0.157s

$ time perl -p -e 's/^(.*)$/\"$1\",/g'  file >/dev/null

real    0m36.576s
user    0m36.006s
sys     0m0.360s
$head-5文件
这是电话线
这是电话线
这是电话线
这是电话线
这是电话线
$wc-l<文件
9545088
$time awk“{print”\042“$0”\042,“}”文件>/dev/null
real 0m15.574s
用户0m15.327s
sys 0m0.172s
$time sed's/*/“&”,/”文件>/dev/null
实际0m31.717s
用户0m31.465s
sys 0m0.157s
$time perl-p-e的/^(.*)$/\“$1\”,/g'文件>/dev/null
实际0m36.576s
用户0m36.006s
sys 0m0.360s
在vi中:

:%s/^\(.*\)$/"\1",/g
蟒蛇


你想对输出做什么?用你的编程语言把它放在一个列表变量中?打印到屏幕上?写回文件?写回文件或打印到屏幕上…我以后会想复制并粘贴到其他地方,这样写回同一个文件或打印到屏幕上就可以了y稍后“手动”复制并粘贴它…将它输出到何处?此文件或屏幕?
perl-pli-e'$\uqq{“$\uqq}“
也可以做这项工作。这就是精神所在,既然你可以使用python!+1作为非常方便的文件输入模块,为什么还要使用gnu呢?不需要重定向,
sed
接受文件名作为参数。
awk
将接受输入文件作为命令行参数,而不需要重定向。我想你想把逗号移到后面引号;除此之外,答案很简洁!
sed的/*/“&”、/“input_file|xclip
:%s/^\(.*\)$/"\1",/g
for line in open("file"):
  line=line.strip()
  print '"%s",'  % line