Reputation: 3218
I have a list:
1 name1
2 name2
3 name3
I need to replace all 1,2,3... to '1', '2', '3'...and name1, name2, name3 to 'name1', 'name', 'name'3. I know how to do it via '\n' and '\s'.
But I think the better way exists. Does anybody know this way?
Upvotes: 1
Views: 569
Reputation: 10650
you can do it easily with perl,
on a unix machine, from the terminal:
perl -pe 's/regex/replace/' input > output
(the > output is optional, and it will just get printed to the terminal)
so:
perl -pe "s/([0-9]+)\s(.*)/'\1' '\2'/g" file > file2
That will find at least one number at the beginning, and capture it (as \1). then some white space, then the rest of the line, captured (as \2). the after the / is the replace bit. just add in the ' s and insert the captured bits.
(if you're on windows, you can get perl here: http://www.perl.org/get.html#more)
Upvotes: 2
Reputation: 30671
Here is a JavaScript solution:
str = str.replace(/(\w+)/g, "'$1'");
Upvotes: 2
Reputation: 2960
Heres a little snippet in PHP:
$str = "1 name1\n2 name2\n3 name3";
$str2 = preg_replace('!([^\s]+)\s([^\n]+)!sm', "'$1' '$2'", $str);
echo $str2;
It uses $1 and $2 to reference the rounded bracket you 'catched' in the string
Upvotes: 1