I would like to write a shell script that would call less to open a text file.
less filename.txt
I then would like the script to search forward through the file using /'search string' or search back using ?'search string'. I also want the script to read the results into variables.
I can get a script to call less to open the file , but how do I get bash to call a series of less commands once the file is opened? Can this be done?
You cannot do it with less
from within a script. There is no language that would control less once you turn control over to it. In order to do what you want, the easiest way is to use grep
. For example, you can read the matching text into an array in bash with:
declare -a results
IFS=$'\n' # set IFS to only break on newline
results=( $(grep $srchterm $filename) ) # read results into array
<parse as necessary>
A second option would be to use while read -r line; do... done <<< $(grep $srchterm $filename)
to essentially do the same thing.
In either case, this allows you to get the wanted lines of text into variables into your script. You can then further parse the lines into additional variables using pattern matching and substring extraction. If you do not use grep
, then your alternative is to read the file line-by-line and manually search for the text of interest. grep
simply automates the search part of the process for you.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments