I needed to replace text in multiple files on an Ubuntu server.
The text was “D:/FTPdownloads”, and would be changed to “srv/ftp” (migrating an FTP server from Windows to Linux). Also this had to be done in 100+ files in a bunch of directories. Quickest way I found to do this was the following:
1 |
find -name "*" -type f | xargs sed -i "s/D:\/FTPdownloads/srv\/ftp/" |
explanation:
1 |
find -name "*" -type f | |
find with a name that can be anything, of type ‘file’, the pipeline hands the output to the next part
1 |
xargs |
xargs builds commandlines with the next command, combined with the output from the previous command
1 |
sed -i "s/D:\/FTPdownloads/srv\/ftp/" |
sed replaces text with the s prefix, and the -i makes sure the input file is also used for output.
This worked well as the directories only contained small config files, if there had also been a bunch of big files you’d be smart to limit finding ‘all’ files. You could play with the “*” part to limit the files it finds. For example, to find all files without an extension:
1 |
find ! -name "*.*" -type f | xargs sed -i "s/D:\/FTPdownloads/srv\/ftp/" |
“*.*” finds only files *with* an extension, and the ! inverts that.