This question is very specific to the structure of an AWK program (with function) provided in response to Print columns using string variable in AWK.
Those responding to my initial question have helped me partially understand the solution provided. I attempted to write the provided program as a single line as I thought it would help me understand more, but ended up in a complete mess. I have now taken the solution and added a new function in my bash script.
create_selected() {
echo ............creating selected ..............
awk -F "," -v cols=$Columns '
BEGIN {
n=split(cols,Fields,/,/)
}
function _get_cols(i,s){
for(i=1;i<=n;i++) s = length(s) ? s OFS $(Fields[i]) : $(Fields[i])
return s
}
{
print _get_cols()
}' myfile.csv
}
The above works well, but only partly reaches my object. I need to only return the columns (as specified by $Columns) in myfile.csv that have a given string within the line. The string is captured elsewhere in the script as $Searchfor.
I believe I must 'pass' this string to awk, and then /Search/ each line. My attempts have failed. This may be due to my lack of understanding of the awk 'BEGIN{} {BODY} END{}' blocks, or perhaps my understanding of how the above solution works. Perhaps it simply doesn't allow me to search as well as use a string to define the columns (?)
I have tried several variations, even moving the awk function before BEGIN, which I have seen in examples on the web. My initial attempt is below, which I thought was the most simple, but was my first failure. Am I able to use search in this solution?
create_selected ()
{
echo ............creating selected ..............
awk -F "," -v searched=$Searchfor -v cols=$Columns 'BEGIN{
n=split(cols,Fields,/,/)
}
function _get_cols(i,s){
for(i=1;i<=n;i++) s = length(s) ? s OFS $(Fields[i]) : $(Fields[i])
return s
}
{
/searched/ print _get_cols()
}' myfile.csv
}
result
............creating selected ..............
awk: cmd. line:9: /searched/ print _get_cols()
awk: cmd. line:9: ^ syntax error
Inputs
echo $Columns
1 3 6
echo $Searchfor
dir1
cat myfile.csv
/data/Files/dir1/record_2023-01-11-15-20-00.csv.gz:2023-01-11 15:18:07.634,2023-01-11 15:17:03.683,2023-01-11 15:17:03.763,40,0,5253763,10.106.144.2,34334,157.240.221.34,443,6,281,1,59,1,0,0,0,0
/data/Files/dir2/record_2023-01-11-15-20-00.csv.gz:2023-01-11 15:18:07.634,2023-01-11 15:17:03.683,2023-01-11 15:17:03.763,40,0,5253763,10.106.144.2,34334,157.240.221.34,443,6,281,1,59,1,0,0,0,0
/data/Files/dir3/record_2023-01-11-15-20-00.csv.gz:2023-01-11 15:18:07.634,2023-01-11 15:17:03.683,2023-01-11 15:17:03.763,40,0,5253763,10.106.144.2,34334,157.240.221.34,443,6,281,1,59,1,0,0,0,0
Required Output
/data/Files/dir1/record_2023-01-11-15-20-00.csv.gz:2023-01-11 15:18:07.634 2023-01-11 15:17:03.763 5253763