5

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

For example, don't touch this file:

cat file.txt
ASDF

but remove "ASDF" from this file:

cat file.txt
ASDF
TR422

Because it has other lines than "ASDF".

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

  • 3
    What about a file that contains hello ASDF? Or a file that contains multiple ASDF lines but nothing else? – Gilles 'SO- stop being evil' 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
6

In bash, using sed:

if [[ $(< "$file") != "ASDF" ]]; then
  sed -i '/^ASDF$/d' "$file"
fi
1

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"
  fi
done

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"
else
  rm -- "$tmpfile"
fi
0

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

Pseudocode:

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

A shorter version of enzotib's answer:

[[ $(< "$file") != "ASDF" ]] && sed -i '/^ASDF$/d' "$file"
0

You can do this sed-only, no need for shell tests and whatnot:

sed '1{/^ASDF$/{$q;d;};}' infile

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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