Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

How can I remove a specific string from a file ONLY if there are other lines in the file?

For example, don't touch this file:

cat file.txt

but remove "ASDF" from this file:

cat file.txt

Because it has other characters than "ASDF".

I'll welcome a solution in bash, perl or any other common tool.

share|improve this question
What about a file that contains hello ASDF? Or a file that contains multiple ASDF lines but nothing else? – Gilles Aug 28 '11 at 17:40
ASDF is always in the first line of the files, and matches this: "^ASDF$" – LanceBaynes Aug 28 '11 at 17:46
up vote 6 down vote accepted

In bash, using sed:

if [[ $(< "$file") != "ASDF" ]]; then
  sed -i '/^ASDF$/d' "$file"
share|improve this answer

Assuming your file names don't contain newline characters, this will remove lines containing just ASDF from all files in the current directory, unless the file consists of a single line containing just ASDF. If your sed doesn't have the -i option, output to a temporary file and move it in place afterwards.

grep -l ASDF -- * | while IFS= read -r filename; do
  if ! echo 'ASDF' | cmp -s - "$filename"; then
    sed -i -e '/^ASDF$/d' -- "$filename"

Here's another approach, which removes the ASDF lines, and only overwrites the original file if the new file is neither empty nor identical to the original.

tmpfile=$(mktemp -p "$(dirname -- "$filename")")
sed '/^ASDF$/' <"$filename" >"$tmpfile"
if [ -s "$tmpfile" ] && ! cmp -s -- "$filename" "$filename"; then
  mv -f -- "$tmpfile" "$filename"
  rm -- "$tmpfile"
share|improve this answer

You would want to look for the number of lines in the file.


if (numberOfLines > 1 && file.contains("ASDF")) {
share|improve this answer
what language is this? bash? perl? – LanceBaynes Aug 28 '11 at 21:18
It's pseudocode... – n0pe Aug 28 '11 at 22:38

A shorter version of enzotib's answer:

[[ $(< "$file") != "ASDF" ]] && sed -i '/^ASDF$/d' "$file"
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.