This question already has an answer here:
-
Recursive search and replace in text files on Mac and Linux
14 answers
I have about 100 .txt files that contain plain text. Somehow, some of the data has been corrupted and needs to be found/replaced.
I need to search for the characters'--' and replace it with a long dash: '—'.
Is there a way to do this quickly with a command in terminal?
The names of the .txt files in my directory are numbered sequentially: 1.txt, 2.txt, etc.
Thanks!
GNU sed
:
sed -i 's/--/—/g' *.txt
OSX BSD sed
:
You need to specify a backup file extension. To create a backup file with the extension: .txt.bak
:
sed -i '.bak' 's/--/—/g' *.txt
To completely replace the files, specify an empty extension:
sed -i '' 's/--/—/g' *.txt
sed -i 's/--/–/g' *.txt
ought to work. The -i
flag to sed
makes it act on the files in-place, the s
stands for substitute, and the g
makes it replace multiple occurrences of the pattern on the same line. Look up sed
's documentation for more information.
EDIT: This works on GNU/Linux; it turns out that the syntax is slightly different on OSX (see comments and accepted answer).