3

I want to find all text files in a directory that do not end with the string:

hello world

How can I do this?

  • You mean the last line do not contain hello world at the end or the last line is not hello world – cuonglm Apr 5 '16 at 15:18
  • @cuonglm The last line is not hello world (or maybe hello world\n, depending on how it matches) – becko Apr 5 '16 at 15:30
  • 2
    OP - you should add that to your post (ideally, along with an example). – don_crissti Apr 5 '16 at 16:09
4

Try:

for f in *; do
  if [ -f "$f" ] && [ "$(tail -n1 -- "$f")" != "hello world" ]; then
      printf '%s\n' "$f"
  fi
done
| improve this answer | |
  • I believe this will also print the names of any regular files that don't have the "readable" bit set. Otherwise excellent solution. :) – Wildcard Apr 11 '16 at 5:40
2

Give this tested version a try:

#!/usr/bin/awk -f
BEGIN {
  last=FILENAME;
}
{
  if (last != FILENAME) {
    if (line !~ /^hello world$/ && line != "hello world") {
      print last;
    }
    last=FILENAME;
  }
  line=$0;
}
END {
  if (line !~ /^hello world$/ && line != "hello world") {
      print FILENAME;
  }
}

The test:

$ chmod +x script.awk
$ ls
script.awk  test1.txt  test2.txt  test3.txt

$ ./script.awk $(find . -type f -exec file {} + | fgrep text | cut -d: -f1)

./script.awk
./test1.txt
| improve this answer | |
-2
cd /my/directory/path
for file in *
do
 grep -v '^$' < "${file}" | tail -1 | grep "hello world" > /dev/null; result=${?}
 if [ "${result}" -ne 0 ]
 then
   echo "${file}" 
 fi
done

The grep -v '^$' < "${file}" part eliminates empty lines that might be added to the end. If this is not desired, you can omit that part and start that line as tail -1 < "${file}"

| improve this answer | |
  • 2
    This fails if file contains any character in IFS, and also break with file start with dash. At least, you want to double quotes your variables. – cuonglm Apr 5 '16 at 15:48
  • Since you like braces so much, I actually added the one you were missing, rather than deleting the unmatched one (or the ones you don’t need).  I added the missing quotes (you don’t need to quote ^$, but always quoting regexs is another good habit to get into) and fixed some of the other problems. – G-Man Says 'Reinstate Monica' Apr 11 '16 at 5:37

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.