Useful unix file editing commands

Find and replace text matching a regular expression in a single file

The above command searches for the (something\-[\da-zA-Z]+) regular expression and replaces it whole (because of the parenthesis which means to select the text matching the expression within) with ToReplace. The g in the end indicates that the operation will be applied to all matches in the file as supplied in path/to/file.txt argument. The -i parameter along with '' suggests the sed command to perform the edit on the file itself, without creating a new copy.

Find and replace text matching a regular expression in files matching name

The above command finds file within /base/directory whose names match *.txt format. Later we combine the output of this with xargs which appends each line of output (path to each matching file) to the following sed command. The -n 1 argument to the xargs command tells it to supply each line of argument one by one to the sed command.

Find and replace text matching a regular expression in files whose contents match a regular expression

In the above command we use the basic find command to get a list of files that we want to do the search in. Then we use grep to recursively find in those files. Now in the above command we don’t really need the -r flag for grep because the find command will list full paths to those files, but we would need it if we were doing find on a relative path instead (like .). The -l flag for grep here will only list the paths to the files that it found having the content TextToFindInFiles and not the actual matching contents like it usually prints. This list of the files is then outputted to the xargs command which then subsequently runs the sed command.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.