[Sed] Editing files in place

Sed provides the -i or --in-place option for saving changes made to the file. For example, you can replace all tabs with a space with the following:

sed 's/\t/ /g' -i file.txt


If you want to keep a backup of the file, option also allows you to provide an extension for a backup file. When provided, it will make a copy of the original contents in a file ending with the specified extension. For example, the following will make a backup in file.txt.bak:

sed 's/\t/ /g' -i.bak file.txt

Note that there is no space between the -i and the extension (.bak). If did do that, it will treat the extension as another input file and it give the following error:

sed: can't read .bak: No such file or directory 

Finally, combining this to work code to replace all tabs with spaces in all .txt files:

find . -name '*.txt' -exec sed 's/\t/ /g' -i {} +
Advertisements

One Response to [Sed] Editing files in place

  1. Francis Barber says:

    Perl can do this as well. perl -pi -e ‘s/\t/ /g’ file.txt

    I like this because I’m more confortable in perl than sed.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: