feat(files): add _randomLineFromFile_

This commit is contained in:
Nathaniel Landau
2023-08-29 11:57:22 -04:00
parent 64c8658c8e
commit 69c1b491bb
4 changed files with 175 additions and 135 deletions

View File

@@ -1,2 +1,9 @@
[default.extend-words]
[default]
default.locale = "en_us"
[default.extend-words]
curren = "curren" # Used in the context of '¤100'
nd = "nd" # Used in the context of '2nd'
[files]
extend-exclude = ["test/test_helper"]

View File

@@ -236,6 +236,7 @@ Functions for working with files.
- **`_makeSymlink_`** Creates a symlink and backs up a file which may be overwritten by the new symlink. If the exact same symlink already exists, nothing is done.
- **`_parseYAML_`** Convert a YAML file into BASH variables for use in a shell script
- **`_printFileBetween_`** Prints block of text in a file between two regex patterns
- **`_randomLineFromFile_`** Prints a random line from a file
- **`_readFile_`** Prints each line of a file
- **`_sourceFile_`** Source a file into a script
- **`_createUniqueFilename_`** Ensure a file to be created has a unique filename to avoid overwriting other files

View File

@@ -301,6 +301,13 @@ _testParseYAML_() {
assert_line --index 2 'line 3'
}
@test "_randomLineFromFile_" {
echo -e "line 1\nline 2\nline 3" > testfile.txt
run _randomLineFromFile_ "testfile.txt"
assert_output --regexp "^line [123]$"
}
@test "_sourceFile_ failure" {
run _sourceFile_ "someNonExistentFile"

View File

@@ -749,6 +749,31 @@ _printFileBetween_() (
fi
)
_randomLineFromFile_() {
# DESC:
# Returns a random line from a file
# ARGS:
# $1 (Required) - Input file
# OUTS:
# Returns random line from file
# USAGE:
# _randomLineFromFile_ "file.txt"
[[ $# == 0 ]] && fatal "Missing required argument to ${FUNCNAME[0]}"
local _fileToRead="$1"
local _rnd
[ ! -f "${_fileToRead}" ] \
&& {
error "'${_fileToRead}' not found"
return 1
}
_rnd=$((1 + RANDOM % $(wc -l <"${_fileToRead}")))
sed -n "${_rnd}p" "${_fileToRead}"
}
_readFile_() {
# DESC:
# Prints each line of a file