String length

2 snippets across 2 stacks — Bash & Linux, SQL

SHBash & Linux

String Operations

SH · Bash Scripting
syntax
${#string}          # length
${string:offset:length}  # substring
${string/pattern/replacement}
example
FILEPATH="/opt/app/logs/server.log"
echo "Length: ${#FILEPATH}"
echo "Filename: ${FILEPATH##*/}"
echo "Directory: ${FILEPATH%/*}"
echo "Change ext: ${FILEPATH%.log}.txt"

URL="https://api.example.com"
echo "${URL/#https/http}"
output
Length: 26
Filename: server.log
Directory: /opt/app/logs
Change ext: /opt/app/logs/server.txt
http://api.example.com

Note ## removes longest prefix match, # removes shortest. %% removes longest suffix, % removes shortest. These are pure Bash operations (no subprocess), so they are much faster than calling sed or basename in a loop.

SQLSQL

LENGTH / CHAR_LENGTH

SQL · String Functions
syntax
LENGTH(string)
CHAR_LENGTH(string)
example
SELECT
  first_name,
  CHAR_LENGTH(first_name) AS name_length
FROM users
WHERE CHAR_LENGTH(first_name) > 10;
output
-- first_name  | name_length
-- Christopher | 11

Note CHAR_LENGTH counts characters; LENGTH counts bytes. They differ for multi-byte character sets (UTF-8). Use CHAR_LENGTH for user-facing string length. ANSI standard is CHARACTER_LENGTH.