Remove a Specific Line from a File Without Using Sed or Awk

How to delete from a text file, all lines that contain a specific string?

To remove the line and print the output to standard out:

sed '/pattern to match/d' ./infile

To directly modify the file – does not work with BSD sed:

sed -i '/pattern to match/d' ./infile

Same, but for BSD sed (Mac OS X and FreeBSD) – does not work with GNU sed:

sed -i '' '/pattern to match/d' ./infile

To directly modify the file (and create a backup) – works with BSD and GNU sed:

sed -i.bak '/pattern to match/d' ./infile

sed or other - remove specific html tag text from file

Should I be using the sed command for desired results?

Actually grep suits it better with:

grep -Ev '</(body|html)>' file

Hello World

If you want to remove specific <body>\n</html>\n string only then use this sed that would work with any version of sed:

sed '/<\/body>/{N; /<\/html>/ {N; s~</body>\n</html>\n~~;};}' file

Hello World

How to delete an specific line of a file using POSIX shell scripts?

I am unsure about POSIX compliance, but can suggest using ed to delete the third line of a file as follows:

echo $'3d\nwq' | ed -s YourFile

or, maybe

printf "3d\nwq\n" | ed -s YourFile

Delete specific line number(s) from a text file using sed?

If you want to delete lines from 5 through 10 and line 12th:

sed -e '5,10d;12d' file

This will print the results to the screen. If you want to save the results to the same file:

sed -i.bak -e '5,10d;12d' file

This will store the unmodified file as file.bak, and delete the given lines.

Note: Line numbers start at 1. The first line of the file is 1, not 0.

Delete specific line with sed without deleting other lines with same prefix

If you anchor your sed pattern match to the beginning and end of the line, then it won't also match substrings. Like so:

sed -i "/^${MYARRAY[$index1]}\$/d" "$file"

(Escaping the '$' used to anchor to the end of the line since it's in a double-quoted string.)


edit: That said, it looks to me like you can replace your entire script with this one-line sed program:

sed '1,/@@@/d; /^$/d'

That deletes from the beginning of the file to the first line containing '@@@', then also deletes blank lines, and does it all in a single pass.



Related Topics



Leave a reply



Submit