How to prepend a character to start of each line in 250,000+ line file using a script?

I have text file with 250,000 lines - and I need to append the same single character at the start of each line. I have tried to use various multiline /column edit plugins in Atom and Sublime but they just hang - I guess due to size of file.

Is this something I could do with with a bash/zsh script - or AppleScript/Automator maybe ?


Solution 1:

Prepend each line of a file with a capital A and write a new file-

awk '{print "A"$0}' < FILE > NEWFILE

Solution 2:

To prepend X to the start of every line of file, writing to newfile, in Terminal:

sed 's/^/X/' file > newfile

Here I'm using sed, the Unix stream editor, to use a very simple regular expression to substitute the beginning of every line (the ^ symbol) with an X.

Solution 3:

The stream editor sed is likely the fastest and sharpest tool built for exactly this task.

Use the insert command (the newline after \ is part of the syntax):

sed 'i\
X' file > newfile

$ time sed 'i\                     
X' line250000 >/dev/null

real    0m0.118s
user    0m0.102s
sys     0m0.012s

The delay or overhead for this operation is extremely low making it very efficient for huge files.