Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I search/replace in multiple .txt files quickly from Terminal? [duplicate]

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!

like image 446
Lizza Avatar asked Aug 10 '12 03:08

Lizza


People also ask

How do you do a find replace on multiple text files?

Remove all the files you don't want to edit by selecting them and pressing DEL, then right-click the remaining files and choose Open all. Now go to Search > Replace or press CTRL+H, which will launch the Replace menu. Here you'll find an option to Replace All in All Opened Documents.

How do I find and replace text in multiple files in Linux?

Find and replace text within a file using sed command Use Stream EDitor (sed) as follows: sed -i 's/old-text/new-text/g' input.txt. The s is the substitute command of sed for find and replace. It tells sed to find all occurrences of 'old-text' and replace with 'new-text' in a file named input.txt.

How do I find and replace in multiple files in Notepad++?

Open the text file in Notepad++. In the top menu bar, click Search and select Replace. In the Replace window, on the Replace tab, enter the text you want to find and the text you want to use as a replacement. See our using search and replace and advanced options for further information and help.


1 Answers

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
like image 151
Steve Avatar answered Oct 26 '22 03:10

Steve