Home > Back-end >  Bash to loop over two columns but just print the first columns and on second run the desired command
Bash to loop over two columns but just print the first columns and on second run the desired command

Time:07-22

i have a bash script where i want echo two distinct fields and combine the command output into it to make it a single line.

I am reading from a csv file two columns that's $2 which is a project name and another $NF which is a volume name. where i am running a command against each volume in a for loop to get the data but i want project and $2 also be printed along with each volume name in a echo command So, i could know a particular project have particular data.

below is sample code:

#!/bin/bash
#
s_list=$(cat ldap-project-nismap.csv | tr "," "\t"| awk '{print $2, $NF}'| tr -d '"'|sed 1d|head -5)
echo $s_list
for name in $(echo "$s_list");
  do
    echo -n "$2: $NF"
    # do Some action on "$NF"
    locate $NF
done

CSV DATA SAMPLE:

"DC_oregon-DC01",dnpc,"dbc2002:/proj/dbc2002_dnpc_eaeagle_pd2/q",1000,"761.87",76,economy,"eaeagle_pd2","dbc2002_dnpc_eaeagle_pd2"
"DC_oregon-DC01",dnpc,"dbc2002:/proj/dbc2002_dnpc_eaeagle2_7/q",4096,"3536.99",86,scratch,"eaeagle2_7","dbc2002_dnpc_eaeagle2_7"
"DC_oregon-DC01",dnpc,"dbc2002:/proj/dbc2002_dnpc_eaeagle2_6/q",4096,"2976.74",73,scratch,"eaeagle

Below is the s_list list which contains Project Name and Volume Name.

d62320 fxn3008_d62320 d62200 fxn3008_d62200 d62150 fxn3008_d62150 d62110 fxn3008_d62110 d62100 fxn3008_d62100

Below is what it looks like:

Project_name   Volume_name
d62320         fxn3008_d62320 
d62200         fxn3008_d62200 
d62150         fxn3008_d62150 
d62110         fxn3008_d62110 
d62100         fxn3008_d62100

What is desired:

d62320:fxn3008_d62320:/q/volset/fxn3008_d62320

CodePudding user response:

First, you can get rid of cat tr sed head with a single awk.

Also, the locate command uses a pattern; it might not be a problem with your volumes names but at the very least you need to prepend */ to them.

awk -F, '2 <= NR && NR <= 6 {gsub(/"/,""); print $2,$NF}' file.csv |

while read -r project volume
do
    path=$(locate -n 1 "*/$volume")
    printf '%s:%s:%s\n' "$project" "$volume" "$path"
done

remark: parsing a CSV this way only works when there isn't any comma nor double-quote nor newline embedded in the fields data.

  • Related