Feature Group
bash internal / data manipulations (105)
bash
This demonstrates basic array manipulation in Bash, including accessing elements, counting, slicing, and iterating.
array=(one two three four five six) # Print the first element: echo "${array[0]}" # => "one" # Print all elements: echo "${array[@]}" # => "one two three four five six" # Print the number of elements: echo "${#array[@]}" # => "6" # Print the number of characters in third element echo "${#array[2]}" # => "5" # Print 2 elements starting from fourth: echo "${array[@]:3:2}" # => "four five" # Print all elements each of them on new line. for item in "${array[@]}"; do echo "$item" done
bash internaldata manipulationsarray manipulationbasic array operations
bash
This demonstrates the usage of the printf
command in Bash for formatted output, including strings, integers, floats, and writing to files.
printf "Hello %s, I'm %s" Sven Olga #=> "Hello Sven, I'm Olga printf "1 + 1 = %d" 2 #=> "1 + 1 = 2" printf "This is how you print a float: %f" 2 #=> "This is how you print a float: 2.000000" printf '%s\n' '#!/bin/bash' 'echo hello' >file # format string is applied to each group of arguments printf '%i+%i=%i\n' 1 2 3 4 5 9
bash internaldata manipulationsstring manipulation and expansionsformatted output
bash
This demonstrates special string slicing and substitution using parameter expansion.
name="John" echo "${name}" echo "${name/J/j}" #=> "john" (substitution) echo "${name:0:2}" #=> "Jo" (slicing) echo "${name::2}" #=> "Jo" (slicing) echo "${name::-1}" #=> "Joh" (slicing) echo "${name:(-1)}" #=> "n" (slicing from right) echo "${name:(-2):1}" #=> "h" (slicing from right) echo "${food:-Cake}" #=> $food or "Cake"
bash internaldata manipulationsstring manipulation and expansionsparameter expansionstring slicing
bash
This demonstrates extracting the base filename and directory path from a file path using parameter expansion.
src="/path/to/foo.cpp" base=${src##*/} #=> "foo.cpp" (basepath) dir=${src%$base} #=> "/path/to/" (dirpath)
bash internaldata manipulationsstring manipulation and expansionsparameter expansionpath manipulation