I have the following test.txt file and need to extract certain rows based on "starting position", "length of string" and "string to search for":
1a2b3d
2a3c4d
.....
My script accepts 3 parameters: (starting col pos, length to search for, string to search for) and would like to pass these parameters for awk to extract the records.
Running the script as:
script 2 3 a2b test.txt
would return the first record from the file:
1a2b3d
awk -v search_col_pos=$search_col_pos search_str_len=$search_str_len string_to_search=$string_to_search 'substr($0, search_col_pos, search_str_len) == "string_to_search"' test.txt
where $search_col_pos, $search_str_len, $string_to_search are passed as input parameters to the script.
but code is not working and is returning the following error:
I am quite sure there would be an easier way of doing what you are trying to do, if you would have provide some real input and output files. Nevertheless, I would like to point out the following:
You need a -v option for each variable you're setting; not just the first one.
If there is any chance that string_to_search could contain any whitespace characters or characters that have special meaning to the shell, it will also need to be quoted.
It is generally a good idea to quote all shell variable expansions, but I will assume for now that your script has already verified that $search_col_pos and $search_str_len expand to numeric strings.
And, inside an awk script, putting a variable name in quotes will try to match against the name of the variable instead of the contents of the variable.