gloomydays
gloomydays

Reputation: 45

How to put quotes for all the numbers using regular expression?

I have a file of just numbers all in separate line such as

+11234567890
+11567876788
+11234567811
+10234567823 
//... and so on

How can I put quotes in all the numbers using regular expression like the following using Visual Studio code find and replace?

"+11234567890"
"+11567876788"
"+11234567811"
"+10234567823"

Upvotes: 0

Views: 378

Answers (3)

Grinnex.
Grinnex.

Reputation: 1049

To make this happen you will need to:

  1. Open the file

  2. Read each line of the file and store each line "value" in an array

  3. Write/Overwrite in a new/same file each index of the array and add to it " + array[index] + ". You will need to use " in order to had quotation marks characters. In this case \ is an escape character for the quotation mark.

  4. After writting the line, jump to a new line. Use "\n".

  5. Close the file

FileInputStream on #2 and FileOutputStream on #3. Both with a for cicle

Upvotes: 1

Kevin Hernandez
Kevin Hernandez

Reputation: 1400

I am assuming you are using NodeJS for this or Python3

Node

const readline = require('readline');
const fs = require('fs');

// Initialize readInterface
const readInterface = readline.createInterface({
  input: fs.createReadStream('/path/to/file'),
  output: process.stdout,
  console: false
});


// This gets call on everyline
readInterface.on('line', function(line) {
  var quotedLine = "\"" + line + "\"";
  fs.appendFile("/path/to/file.txt", quotedLine, (err) =>{
    if(err){console.log(err)}
  });
  console.log("Writing Line...");
});

Python3

filepath = 'phonenumbers.txt'

# Open the file
with open(filepath) as phoneNums:
  # Get lines
  line = phoneNums.readline()

  # Iterate through all lines
  while line:
    print("Writing line")

    # Write the quoted lines to a new file
    with open("quoted.txt", 'w') as quotedNumbers:
      quotedNumbers.write("\"" + line + "\"")

Upvotes: 3

PythonNerd
PythonNerd

Reputation: 293

f = open('file.txt', 'r')
for i in f:
  i = '"'+i+'"'

Upvotes: -1

Related Questions