Removing a line of text from a .txt file

JRodgers17
New Contributor III

Hello! 

I am trying to create a script that would remove certain lines/strings from a .txt file. 

I have tried: 
sed "/$String/ d" File.txt

But had no luck, any thoughts or tips? 

1 ACCEPTED SOLUTION

mark_mahabir
Valued Contributor

The sed command you have tried should work to remove the lines containing the specified string. However, there are a few things to keep in mind:

  1. Make sure that $String is properly defined in your script. If the variable is not set correctly, then the sed command will not work as expected.

  2. Make sure that File.txt is the correct file name and that it is in the same directory as your script. If the file is located in a different directory, then you will need to provide the full path to the file.

Here's an example of how you can use sed to remove lines containing a specific string:

#!/bin/bash

# Define the string to remove
string="example"

# Define the file to modify
file="example.txt"

# Use sed to remove lines containing the string
sed "/$string/d" "$file" > temp.txt

# Replace the original file with the modified file
mv temp.txt "$file"

In this example, the sed command is used to remove any line containing the string "example" from the file "example.txt". The modified file is saved as "temp.txt", and then the original file is replaced with the modified file using the mv command.

View solution in original post

2 REPLIES 2

mark_mahabir
Valued Contributor

The sed command you have tried should work to remove the lines containing the specified string. However, there are a few things to keep in mind:

  1. Make sure that $String is properly defined in your script. If the variable is not set correctly, then the sed command will not work as expected.

  2. Make sure that File.txt is the correct file name and that it is in the same directory as your script. If the file is located in a different directory, then you will need to provide the full path to the file.

Here's an example of how you can use sed to remove lines containing a specific string:

#!/bin/bash

# Define the string to remove
string="example"

# Define the file to modify
file="example.txt"

# Use sed to remove lines containing the string
sed "/$string/d" "$file" > temp.txt

# Replace the original file with the modified file
mv temp.txt "$file"

In this example, the sed command is used to remove any line containing the string "example" from the file "example.txt". The modified file is saved as "temp.txt", and then the original file is replaced with the modified file using the mv command.

This did work for me! The issue I believe is that I didn't create a temp text file. Also needed to include the entire location of the file and it worked as expected. Really appreciate the help on this one, thank you!