
Learn through the super-clean Baeldung Pro experience:
>> Membership and Baeldung Pro.
No ads, dark-mode and 6 months free of IntelliJ Idea Ultimate to start with.
Last updated: January 18, 2025
sed is a popular tool for working with text data. However, if not used properly, it may cause errors.
In this tutorial, we’ll look at a situation where sed fails to find a file in a Linux directory.
First, we’ll replicate the sed problem. Then, we’ll learn how to fix it on Linux. Finally, we’ll see why the same sed command fails on Linux but works correctly on macOS.
First, let’s create a sample file with a simple text string using the touch and echo commands:
$ touch test
$ echo "a" > test
Now, we should have a file named test with the string “a” as its content. Let’s check it using the cat command:
$ cat test
a
Here, we can use a simple sed command to replace the “a” string with “b” in the test file:
$ sed -i "" -e 's/a/b/g' test
sed: can't read : No such file or directory
However, we obtain the “No such file or directory” error.
Next, we’ll see how we can resolve this error.
Let’s look at the previous sed command in more detail:
However, we can see that after the -i option, there is an empty double quote (“”).
In fact, sed interprets the expression as if we provided an empty filename to it. This isn’t something we intended to do.
Therefore, to fix the above error, we should remove the “” after the -i option:
$ sed -i -e 's/a/b/g' test
Now, the operation is completed successfully.
Let’s check if the “a” string has changed to the “b” string:
$ cat test
b
Indeed, the test file now contains a “b” string instead of an “a” string.
The reason for adding the empty quotes after the -i option is to avoid the creation of a sed backup file during command execution.
However, this syntax works on macOS only. The GNU sed implementation on Linux works differently. Therefore, we get the above error on Linux.
To make our script agnostic to the OS, we can add a check for the underlying OS:
if [[ "$OSTYPE" == "darwin"* ]]; then
sed -i "" -e 's/a/b/g' test
else
sed -i -e 's/a/b/g' test
fi
As we can see, now we have both options available based on the OS type used.
In this article, we’ve looked at a particular sed command error where sed fails to find a correct filename.
First, we created a sample file and replicated the problem on Linux. Then, we looked at the sed command in more detail and learned how to fix the error. Finally, we examined the difference in the sed implementation between Linux and macOS.