Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to replace a character INSIDE the text content of many files automatically?

Tags:

python

text

r

latex

I have a folder /myfolder containing many latex tables.

I need to replace a character in each of them, namely replacing any minus sign -, by an en dash .

Just to be sure: we are replacing hypens INSIDE all of the tex file in that folder. I dont care about the tex file names.

Doing that manually would be a nightmare (too many files, too many minuses). Is there a way to loop over the files automatically and do the replacement? A solution in Python/R would be great.

Thanks!

like image 487
ℕʘʘḆḽḘ Avatar asked Jul 09 '17 13:07

ℕʘʘḆḽḘ


People also ask

How do I replace text in multiple text files?

Press Ctrl+Shift+F as a shortcut to find a string in multiple files. Press Ctrl+Shift+H as a shortcut to find and replace a string in multiple files.

How do I find and replace in multiple files?

Open Notepad++ and go to Search > Find in Files... or press CTRL+SHIFT+F. This opes the Find in Files menu. Under Find what:, enter the word or phrase that you need to change. Under Replace with:, enter the new word or phrase.

How do you replace a string that occurs multiple times in multiple files inside a directory in Unix?

s/search/replace/g — this is the substitution command. The s stands for substitute (i.e. replace), the g instructs the command to replace all occurrences.


1 Answers

sed -i -e 's/-/–/g' /myfolder/* should work.

The expression does a search globally and replaces all - inside the files the shell expands from /myfolder/* with . Sed does the change in-place, that is, overwriting the original file (you need to explicitly specify a backup-file on MacOS, I can't remember the parameter though).

Absolutely no care is taken about wether or not the - is a verbatim hyphen or part of the latex syntax. Be aware of that.

like image 138
user2722968 Avatar answered Oct 23 '22 14:10

user2722968