4

I am very new to shell programming. I have a file named quaternary_splitted.csv on macOS. Every line has 4 words. I want to take every word from each line and assign it to a variable. Please suggest some kind of awk command in for loop
The value of each of those 4 variable I want to use further in my shell program.

Thanks for the help. Few of the lines from the file:

Ta Cr Mo W  
Nb Cr Mo W  
Nb Ta Mo W  
Nb Ta Cr W  
Nb Ta Cr Mo
  • 1
    Why awk? I mean, awk does this automatically: awk '{print $3}' file will print the 3rd field. Is that what you mean, or do you want to do this in the shell? – terdon Sep 14 at 17:18
  • @terdon: grumble grumble Please don't reinvent the cut(1) wheel with awk, it makes things harder to read, and some of us actually have to maintain our terrible shell scripts... – Kevin Sep 15 at 1:47
6

You can do this with a while read loop like so:

while read -r col1 col2 col3 col4 trash; do
    something with "$col1"
    something with "$col2"
    something with "$col3"
    something with "$col4"
done < /path/to/quaternary_splitted.csv

This will read through each line of quaternary_splitted.csv and set the first column to col1, second column to col2, etc.

The trash parameter is used to catch anything that may be in your file and unwanted. Say you had a line: Nb Ta Cr W what is this doing here?. Without trash you would get:

col1=Nb
col2=Ta
col3=Cr
col4='W what is this doing here?`
  • Thanks for the help. It worked. – Sufyan Sep 17 at 4:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.