Often you may want to use Bash to sort the lines of a file in-place.
The easiest way to do so is by using the sort command with the -o option as follows:
sort -o teams.txt teams.txt
This particular example sorts the lines of the file named teams.txt and saves the results to the file in-place.
Note that we use the -o option to specify the name of an output file to be used instead of the standard output.
By using the same output file name as the input file name, we are able to sort the rows of a file and save the results to the same file in-place.
Note that you can also use the following syntax to sort a file in-place with less code:
sort -o teams.txt{,}
The following example shows how to use this syntax in practice.
Example: How to Use Bash to Sort a File In-Place
Suppose that we have a text file named teams.txt that contains the names of various basketball teams:

Suppose that we would like to sort the rows of the file based on team name in alphabetical order.
If we simply use the sort command to do so, the sorted rows will be shown in the output but the file will not be sorted in-place:

Notice that when we use the cat command to view the file again we can see that the rows have not been sorted in the file itself.
Instead, we must use the sort command with the -o option as follows:
sort -o teams.txt teams.txt
The following screenshot shows how to use this syntax in practice:

Notice that when we use the cat command to view the contents of the original teams.txt file we can see that the rows in the file have been sorted in-place.
Feel free to use similar syntax to sort your own file in-place.
Related Tutorials
The following tutorials explain how to perform other common tasks in Bash:
Bash: How to Sort File by Multiple Columns
Bash: How to Sort by Last Column in File
Bash: How to Sort a File by Line Length
