Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Getting last X records from CSV file using bash

I’m trying to get as bash variable list of users which are in my csv file. Problem is that number of users is random and can be from 1-5.

Example CSV file:

"record1_data1","record1_data2","record1_data3","user1","user2"
"record2_data1","record2_data2","record2_data3","user1","user2","user3","user4"
"record3_data1","record3_data2","record3_data3","user1"

I would like to get something like

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

list_of_users="cat file.csv | grep "record2_data2" | <something> "
echo $list_of_users
user1,user2,user3,user4

I’m trying this:

cat file.csv | grep "record2_data2" |  awk -F, -v OFS=',' '{print $4,$5,$6,$7,$8 }' | sed 's/"//g'
    

My result is:

user2,user3,user4,,

Question:
How to remove all "," from the end of my result? Sometimes it is just one but sometimes can be user1,,,,
Can I do it in better way? Users always starts after 3rd column in my file.

>Solution :

This will do what your code seems to be trying to do (print the users for a given string record2_data2 which only exists in the 2nd field):

$ awk -F',' '{gsub(/"/,"")} $2=="record2_data2"{sub(/([^,]*,){3}/,""); print}' file.csv
user1,user2,user3,user4

but I don’t see how that’s related to your question subject of Getting last X records from CSV file using bash so idk if it’s what you really want or not.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading