Skip to content

Commit

Permalink
Added "search" action to "line_in_file" function
Browse files Browse the repository at this point in the history
  • Loading branch information
jaydrogers committed Sep 17, 2024
1 parent eb73040 commit 4433998
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ line_in_file [--file FILE] [--action ACTION] [ARGUMENTS...]
| Parameter | Description | Required | Default |
|-----------|-------------|----------|---------|
| `--file FILE` | Specifies the target file(s) to modify. Can be used multiple times for multiple files. | Yes | N/A |
| `--action ACTION` | Determines the operation to perform. Available actions: `ensure`, `replace`, `after`, `exact`. | No | `ensure` |
| `--action ACTION` | Determines the operation to perform. Available actions: `ensure`, `replace`, `after`, `exact`, `search`. | No | `ensure` |
| `ARGUMENTS` | The content to manipulate, which varies based on the chosen action. | Yes | N/A |

#### Actions
Expand All @@ -136,6 +136,7 @@ line_in_file [--file FILE] [--action ACTION] [ARGUMENTS...]
| `replace` | Replaces a line containing specific content with a new line. | Two arguments: search content and replacement line. | Appends the replacement line to the file. |
| `after` | Inserts a new line after a line containing specific content. | Two arguments: search content and line to insert. | Appends both the search content and new line to the file. |
| `exact` | Performs an exact replacement of text within the file. | Two arguments: exact text to replace and replacement text. | Returns an error. |
| `search` | Searches for specified content in the file. | One argument: content to search for. | Returns false (exit code 1). |

#### Usage Examples

Expand Down
12 changes: 8 additions & 4 deletions lib/functions.sh
Original file line number Diff line number Diff line change
Expand Up @@ -642,16 +642,13 @@ line_in_file() {
return 1
fi

if [[ ${#args[@]} -eq 0 ]]; then
if [[ ${#args[@]} -eq 0 && "$action" != "search" ]]; then
echo "Error: No content specified" >&2
return 1
fi

# Process each file
for file in "${files[@]}"; do
# Create file if it doesn't exist
[[ -f "$file" ]] || touch "$file"

case $action in
ensure)
for line in "${args[@]}"; do
Expand Down Expand Up @@ -700,6 +697,13 @@ ${args[1]}" "$file"
return 1
fi
;;
search)
if grep -qF -- "${args[0]}" "$file"; then
return 0 # True, content found
else
return 1 # False, content not found
fi
;;
*)
echo "Error: Invalid action '$action'" >&2
return 1
Expand Down

0 comments on commit 4433998

Please sign in to comment.