Home > Enterprise >  How to look for files that have an extra character at the end?
How to look for files that have an extra character at the end?

Time:07-19

I have a strange situation. A group of folks asked me to look at their hacked Wordpress site. When I got in, I noticed there were extra files here and there that had an extra non-printable character at end. In Bash, it shows it as a \r.

enter image description here

Just next to these files with the weird character is the original file. I'm trying to locate all these suspicious files and delete them. But the correct Bash incantation is eluding me.

find . | grep -i \? and find . | grep -i '\r' aren't working

How do I use bash to find them?

CodePudding user response:

Remove all files with filename ending in \r (carriage return), recursively, in current directory:

find . -type f -name $'*\r' -exec rm -fv {}  
  • Use ls -lh instead of rm to view the file list without removing.
  • Use rm -fvi to prompt before each removal.
  • -name GLOB specifies a matching glob pattern for find.
  • $'\r' is bash syntax for C style escapes.
  • You said "non-printable character", but ls indicates it's specifically a carriage return. The pattern '*[^[:graph:]' matches filenames ending in any non printable character, which may be relevant.
  • To remove all files and directories matching $'*\r' and all contents recursively: find . -name $'*\r' -exec rm -rfv {} .

CodePudding user response:

You have to pass carriage return character literally to grep. Use ANSI-C quoting in Bash.

find . -name $'*\r'
find . | grep $'\r'
find . | sed '/\x0d/!d'

CodePudding user response:

if it a special character

Recursive look up

 grep -ir $'\r'

# sample output
# empty line

Recursive look up just print file name

 grep -lir $'\r'

# sample output
file.txt

if it not a special character

You need to escape the backslash \ with a backslash so it becomes \\

Recursive look up

grep -ir '\\r$`

# sample output
file.txt:file.php\r

Recursive look up just print file name

grep -lir '\\r$`

# sample output
file.txt

help:

  • -i case insensitive
  • -r recursive mode
  • -l print file name
  • \ escape another backslash
  • $ match the end
  • $'' the value is a special character e.g. \r, \t

CodePudding user response:

shopt -s globstar # Enable **
shopt -s dotglob  # Also cover hidden files
offending_files=(**/*$'\r') 

should store into the array offending_files a list of all files which are compromised in that way. Of course you could also glob for **/*$'\r'*, which searches for all files having a carriage return anywhere in the name (not necessarily at the end).

You can then log the name of those broken files (which might make sense for auditing) and remove them.

  •  Tags:  
  • bash
  • Related