tags:

views:

785

answers:

5

I need script to add quotes in url string from url.txt

from http://www.site.com/info.xx to "http://www.site.com/info.xx"

+3  A: 
url = '"%s"' % url

Example:

line = 'http://www.site.com/info.xx  \n'
url = '"%s"' % line.strip()
print url # "http://www.site.com/info.xx"

Remember, adding a backslash before a quotation mark will escape it and therefore won't end the string.

Evan Fosmark
A: 

write one...
perl is my favourite scripting language... it appears you may prefer Python.

just read in the file and add \" before and after it..
this is pretty easy in perl.

this seems more like a request than a question... should this be on stackoverflow?

gnomed
No question is too trivial on StackOverflow.
strager
Personally, I think it would be easier to add the quotes on output (i.e. print "\"$url\"\n";), but however you want to do it.
Chris Lutz
+3  A: 
url = '"%s"' % url

Example:

>>> url = "http://www.site.com/info.xx"
>>> print url
http://www.site.com/info.xx
>>> url = '"%s"' % url
>>> print url
"http://www.site.com/info.xx"
>>>

Parsing it from a file:

from __future__ import with_statement

def parseUrlsTXT(filename):
    with open(filename, 'r') as f:
        for line in f.readlines():
            url = '"%s"' % line[:-1]
            print url

Usage:

parseUrlsTXT('/your/dir/path/URLs.txt')
Andrea Ambu
`.readlines()` is redundant (`f` object is already an iterator over lines in the file). `for line in fileinput.input(): print '"%s"'%line.rstrip()` will work both for files and stdin.
J.F. Sebastian
A: 

If 'url.txt' contains a list of urls, one url per line then:

  • quote the first non-whitespace character sequence:

    $ perl -pe"s~\S+~\"$&\"~" url.txt
    
  • or trim whitespaces and quote the rest:

    $ perl -nE"$_=trim; say qq(\"$_\")" url.txt
    
J.F. Sebastian
There is no trim function in Perl, not even in 5.10. Perhaps you mean perl -nE 's/^\s*(.*)\s*$/$1/; say qq/"$_"/' url.txt
Chas. Owens
Also, depending on the shell you are using, you may need to escape the $_ in your examples to prevent the shell variable $_ (rather than the Perl variable) from being interpolated into the program.
Chas. Owens
A: 

A simple Perl script:

#!/usr/bin/perl

use strict;
use warnings;

while (my $line = <>) {
    $line =~ s/\s*(.*)\s*/$1/;
    print qq/"$line"\n/;
}
Chas. Owens