command line substring linux 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: substring in shell script

STR="birthday-091216-pics"
SUBSTR=$(echo $STR | cut -d'-' -f 2)
echo $SUBSTR