dylanaraps / pure-bash-bible

📖 A collection of pure bash alternatives to external processes.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Alternative to strings

opened this issue · comments

strings() {
# Usage: strings [FILE]
local IFS line
while read -r line; do
    printf -- '%s\n' "${line//[^[:alnum:][:blank:][:punct:]]}"
done < "${1}"
}

A slight improvement:

strings() {
  if (($#)); then
    strings < "$1"
    return
  fi
  local IFS line
  while read -r line; do
    printf -- '%s\n' "${line//[^[:alnum:][:blank:][:punct:]]}"
  done
}

will allow reading from stdin. For example:

 cat /bin/bash | strings

A slight improvement:

strings() {
  if (($#)); then
    strings < "$1"
    return
  fi
  local IFS line
  while read -r line; do
    printf -- '%s\n' "${line//[^[:alnum:][:blank:][:punct:]]}"
  done
}

will allow reading from stdin. For example:

 cat /bin/bash | strings

Great! Thank you

Additionally [:alnum:][:blank:][:punct:] can be shorten to [:print:]:

strings() {
if (($#)); then
  strings < "${1}"; return 0
fi
local IFS line
while read -r line; do
  printf -- '%s\n' "${line//[^[:print:]]}"
done
}

The above is skipping spaces/tabs at the lines' start in a file. Fixed here:

strings() {
if (($#)); then
  strings < "${1}"; return 0
fi
local IFS line
while IFS="" read -r line; do
  printf -- '%s\n' "${line//[^[:print:]$'\t ']}"
done
}