Replace Text in a File using the Command Line
This page answers questions like these:
- How to replace a string in a file?
- How to do an in-file replace using Sed?
- How to do an inline replace using Perl?
- How to do an in-place replace using Sed?
- How to do an in-place replace using Perl?
- How to replace a regular expression throughout a file?
Related Links:
Count Occurrences of a Hexadecimal Sequence in a File
Count Occurrences of a String in a File
Find Positions of a Hexadecimal Sequence in a File
Join Lines of Text File Together
Output Lines of a File in Reverse Order
Output the Lines Between Two Matching Lines
Sed Cannot Rename Temporary File Permission Denied
Replacing Text using Perl:
perl -p -i[EXTENSION] -e 's/FROM/TO/g' FILE ...
- If EXTENSION is present, rename each file FILE to file FILEEXTENSION.
- Replace text "FROM" with text "TO" everywhere in every FILE.
- Pros: Handles multiple files. FROM can be a regular expression.
- Cons: May not handle symbolic links the way you want to: Symbolic links will get moved. New file will not be a symbolic link.
Example:
perl -p -i.bak -e 's/YES/NO/g' file1 file2
- Rename "file1" to "file1.bak".
- Rename "file2" to "file2.bak".
- Replace text "YES" with text "NO" everywhere in both file1 and file2.
Replacing Text using Sed:
sed -i[EXTENSION] [--follow-symlinks] 's/FROM/TO/g' FILE ...
- If EXTENSION is present, make a backup first by renaming each file FILE to file FILEEXTENSION.
- If --follow-symlinks present, and a file is a symbolic link, follow the link and create the backup in the same directory as the real file, i.e. preserve the symbolic link.
- Replace text "FROM" with text "TO" everywhere in every FILE.
- Pros: Handles multiple files. FROM can be a regular expression.
- Cons: May not handle symbolic links the way you want to: If --follow-symlinks not present, symbolic links will get moved, and the new file will not be a symbolic link. If --follow-symlinks present, backup files will get created in the same directory as where the target of the link resides.
- Caveats: Will destroy symbolic links if either --follow-symlinks or EXTENSION not present. Sed doesn’t replace overlapping patterns.
Related Links:
Count Occurrences of a Hexadecimal Sequence in a File
Count Occurrences of a String in a File
Find Positions of a Hexadecimal Sequence in a File
Join Lines of Text File Together
Output Lines of a File in Reverse Order
Output the Lines Between Two Matching Lines
Sed Cannot Rename Temporary File Permission Denied
Home > Linux / Unix > Replace Text in a File using the Command Line
Tags: text replace, string replace, in-place replace, inline replace, in-file replace, in-place text replace, inline text replace, in-file text replace, text substitution, perl, sed, linux, unix, solaris, bsd, aix
Copyright © HelpDoco.com
file-replace-text-in-place.txt
Linux-Unix/in-file-text-replace-using-perl-or-sed.htm
2