Python or bash - adding "at the beginning of a line and" at the end of a line

I have a text file with something like

first line
line nr 2
line three

etc.

And I want to generate

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

I wonder how to do this in python, or perhaps in bash, if it's easier / faster. I know that there is different code for opening a file and differs for reading only one line in python (?), But I'm not sure which option to use in this case and, more importantly, how to add these characters. Any advice would help.

+2
source share
9 answers

A few easy ways to do this ...

Simple perl oneliner:

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

, ^(.*)$ ((.*)) (^) ($), $1 , .

+4
sed 's/.*/"&",/'
+8

, - , python. fileinput, :

import fileinput
import sys, os

for line in fileinput.input(inplace=True):
    sys.stdout.write('"%s",%s' % (line.rstrip(os.linesep), os.linesep))

script:

python myscript.py file1 file2 file3

.

+6

unix: sed!

sed 's/^/"/; s/$/",/;' < your_text_file

, 's/"/\\"/g; s/^/"/; s/$/",/;' .

sed . .

+6

There is no need to create a regular expression (with a reverse request) for this task. This is an expensive operation since you are not going to change anything in the line. The easiest way is to simply print them.

    awk '{print "\042"$0"\042,"}' file 

The results of work in a large 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
+5
source

In Bash:

while read line
    do
    echo "\"${line}\","
done < inputfile
+1
source

Python

for line in open("file"):
  line=line.strip()
  print '"%s",'  % line
+1
source

sh + awk are good here too ...

!/bin/sh
for FILE in "$@"
do
   awk '{print "\" $0 "\","}' < $FILE > $FILE.tmp
   mv $FILE.tmp $FILE
done
0
source

In vi:

:%s/^\(.*\)$/"\1",/g
0
source

All Articles