What is the sed in-place flag that works both on Mac and Linux?

The sed command in Linux stands for stream editor and is mainly used to perform functions on files, such as searching, replacing, or inserting text. It is a very useful command-line utility available on Linux systems.

However, there's an important difference between operating systems: the BSD sed shipped with macOS requires a mandatory argument with the -i flag, while GNU sed on Linux makes this argument optional.

The Cross-Platform Solution

The most reliable way to make sed work identically on both Mac and Linux is to use the -i flag with a backup extension. This approach works on both BSD and GNU versions of sed.

sed -i.bak 's/old_text/new_text/' filename

This command creates a backup file with the .bak extension before performing the in-place edit, ensuring compatibility across both systems.

Alternative Approach − Installing GNU sed on Mac

You can install GNU sed on macOS to maintain consistency with Linux systems:

brew install gnu-sed --with-default-names

This installs GNU sed and makes it available as the default sed command on macOS.

Example − Cross-Platform Usage

Let's demonstrate how the -i.bak approach works on both systems:

On GNU Linux

$ sed --version | head -1
GNU sed version 4.2.2

$ echo 'sample' > 1.txt

$ sed -i.bak 's/sample/new_sample/' ./1.txt

$ ls
1.txt 1.txt.bak

$ cat ./1.txt
new_sample

On Mac OS X

$ sed --version 2>&1 | head -1
sed: illegal option -- -

$ echo 'sample' > 1.txt

$ sed -i.bak 's/sample/new_sample/' ./1.txt

$ ls
1.txt
1.txt.bak

$ cat ./1.txt
new_sample

Key Differences

System sed Version -i Flag Behavior Backup Extension
Linux GNU sed Optional argument Optional
macOS BSD sed Mandatory argument Required

Best Practices

  • Always use -i.bak for maximum compatibility between Mac and Linux

  • Remove backup files manually after confirming the edit was successful

  • Use an empty extension -i '' only when you're certain about GNU sed availability

Conclusion

The sed -i.bak approach provides the most reliable cross-platform solution for in-place file editing. By specifying a backup extension, you ensure compatibility between BSD sed on macOS and GNU sed on Linux while maintaining a safety net through automatic backups.

Updated on: 2026-03-17T09:01:38+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements