This section covers various file manipulation functions that can be useful in bash scripting.
The replaceInFile function replaces specified text in a file with new text.
replaceInFile <file> <search> <replace>
- : The path to the file where the replacement should be performed.
- : The text to search for in the file.
- : The text to replace the matched occurrences with.
replaceInFile file.txt "foo" "bar"
The fileExists function checks if a file exists.
fileExists <file_path>
- <file_path>: The path to the file to check. Returns
- 0 if the file exists.
- 1 if the file does not exist.
if fileExists file.txt; then
echo "File exists"
else
echo "File does not exist"
fi
The directoryExists function checks if a directory exists.
directoryExists <dir_path>
<dir_path>: The path to the directory to check. Returns 0 if the directory exists. 1 if the directory does not exist.
if directoryExists /path/to/directory; then
echo "Directory exists"
else
echo "Directory does not exist"
fi
The extractColumn function extracts a column from a CSV file.
extractColumn <file> <column>
- : The path to the CSV file.
- : The column number to extract.
extractColumn data.csv 2
The filterLines function filters lines of a file by a pattern.
filterLines <file> <pattern> <separator>
- : The path to the file.
- : The pattern to filter the lines by.
- : The separator to use for the filtered lines. Use "newline" for a newline-separated output.
filterLines file.txt "pattern" ","