Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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
ASDF

but remove "ASDF" from this file:

cat file.txt
ASDF
TR422

Because it has other characters than "ASDF".

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

share|improve this question
3  
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
add comment

4 Answers

up vote 6 down vote accepted

In bash, using sed:

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

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
share|improve this answer
add comment

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

Pseudocode:

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

A shorter version of enzotib's answer:

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

Your Answer

 
discard

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.