Nullpointer
Nullpointer

Reputation: 1086

Edit multiple files in ubuntu

I have multiple(more than 100) .c files and I want to change a particular text from all the file in which that text exists. I am using ubuntu!

How can I do it?(I will prefer command line rather than installing any application)

Thanks a lot!

Upvotes: 0

Views: 137

Answers (2)

Shlomi
Shlomi

Reputation: 4746

You should check out sed, which lets your replace some text with other text (among other things)

example

sed s/day/night/ oldfile newfile

will change all occurences of "day" with "night" in the oldfile, and store the new, changed version in the newfile

to run on many files, there are a few things you could do:

  • use foreach in your favorite shell
  • use find like this find . -name "namepattern" -exec sed -i "sed-expr" "{}" \;
  • use file patterns like this: sed -i "sed-expr" *pattern?.cpp

where *pattern?.cpp is just a name pattern for all files that starts with some string, then has "pattern" in them, and has any letter and a ".cpp" suffix

Upvotes: 0

wolfrevo
wolfrevo

Reputation: 7303

OLD=searchtext
NEW=replacedtext
YOURFILE=/path/to/your/file
TMPFILE=`mktemp`
sed "s/$OLD/$NEW/g" $YOURFILE > $TMPFILE && mv $TMPFILE $YOURFILE
rm -rf $TMPFILE

you can also use find to find your files:

find /path/to/parent/dir -name "*.c" -exec sed 's/$OLD/$NEW/g' {} > $TMPFILE && mv $TMPFILE {} \;

find /path/to/parent/dir -name "*.c" finds all files with name *.c under /path/to/parent/dir. -exec command {} \; executes the command in the found file. {} stands for the found file.

Upvotes: 1

Related Questions