2

I'm looking for a way to add a character at beginning and at the end of each line of a txt file. The file contains a list of http addresses and I'd like to add the character " without any space, at the beginning and at the end of each address.

2
  • Do you have some empty lines as well? – Kulfy Jul 18 '20 at 8:02
  • Hello @Kulfy there are any empty line. – Gennaro Arguzzi Jul 18 '20 at 8:17
3

If python is not an option, you can use sed:

sed -i 's/^\(.*\)$/"\1"/' file

Brief explaination:

  • -i: in-place (edit files in place )
  • s/^\(.*\)$/"\1"/: this replaces all the content that matches the regular expression delimited by the first two slashes (in this case ^\(.*\)$ matches each line and saves the content of the line in the \1 group, which will be used during the replacement) with the corresponding one between the last two slashes (in this case "\1" adds the quotes at the beginning and at the end of the group saved before).
1
  • 2
    fyi you can avoid an explicit capture group in this case by using the special & replacement character: sed 's/.*/"&"/' – steeldriver Jul 18 '20 at 12:08
3

Using sed:

sed 's/^/"/;s/$/"/' filename

^ denotes the starting of line and $ ending of line.

If you want to overwrite the file, use -i option.

sed -i 's/^/"/;s/$/"/' filename
2

You could use python for it.

Just copy paste this code in a file called test.py and run it using python3

file = open("/PATH/temp.txt", "r")

text = file.readlines()
file.close()
text2 = []
for x in text:
    if x[-1] == '\n':
        text2.append('"' + x[:-1] + '"')
    else:
        text2.append('"' + x + '"')

for x in text2:
    print(x)

file = open("/PATH/temp.txt", "w")
for x in text2:
    file.write(x + '\n')

file.close()

Edit the first and fourthlast line with appropriate path to the txt file you want to edit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.