substr bash code example

Example 1: bash print substring of a field

# Basic syntax:
awk 'BEGIN {FS="input_delimiter"; OFS="output_delimiter"} {print substr($column_number, start_character, number_characters)}' input_file

# Where:
#	- BEGIN {FS="input_delimiter"; OFS="output_delimiter"} is for setting
#		the input and output field/column delimiters
#	- column_number is the field for which you want a substring
#	- start_character is the number of the first character from the left
#		(inclusive) that you want to incude in the substring
#	- number_characters is the number of characters to print past the 
#		start character (inclusive)

# Example usage:
# Say you had a file like the following and only want the ID #s:
customer	info	ID:123456	account
customer	info	ID:172327	account

# Running:
awk 'BEGIN {FS="\t"; OFS="\t"} {print substr($3, 4, 6)}' input_file

# Would return:
123456
172327

Example 2: how to print substring in bash script

INPUT='someletters_12345_moreleters.ext'
SUBSTRING=$(echo $INPUT| cut -d'_' -f 2)
echo $SUBSTRING