Search code examples
bashcut

Extract two Columns from CSV file, split them in while read loop and do different commands with each string


first I must admit, that I am a noobie with the bash and I am sorry if I did any stupid mistakes. I searched a lot, but I think I am missing the basics.

What I want to do:

  • read a csv-file
  • get the content of two columns
  • create a file with first columns as filename
  • and put the content of the second column in that file.

EDIT: This is the sample data:

column1;column2;column3-iwant;column4;column5 is what i want;;;
loerm ipsum; dolor sit ame;filename;consetur;the content i want in the file;;;
justo;labore;myfilename2;labore;;sometimes something here;

My first attempt was very promising:

cut -d\; -f3,5 myFile.csv | while read line; do echo $line; done

I get the following output:

filename1; Value1, Value2, Value3
filename2, Value B, ValueC, ValueD

What I now want to do is split this string with ";" as delimiter and create a file "filename1.txt" and put the content "Value1, Value2, Value3" in this file.

I tried the next step as follows

cut -d\; -f3,5 myFile.csv | while read line; do filname=$(echo "$line" | cut -d\; -f1) | echo $filename; done

This prints $line for every loop

Next bet:

cut -d\; -f3,5 myfile.csv | while read line; do filename=`echo $line | cut -d\; -f1` | mycontent=`echo $line | cut -d\; -f2` | echo "$filename"; done

Quite close but it prints for every loop the last row of the csv-file.

What is my mistake? Cheers David


Solution

  • David!

    I am a newbie here as well, but I think I have the answer.

    If you create a script file with this content and make it executable, you can then type ./script.bash NameOfMyFile.csv and it will do your trick. You can at least use this code as a place to start. Good luck!

    #!/bin/bash
    file=$1
    while IFS=';' read -r newfile contents 
    do
       echo "Create file: $newfile  ==> with contents: $contents"
       echo $contents > $newfile
    done < "$file"
    

    The sample file I fed it looked like this:

    Name1; Put this stuff in the first place I want it And then put in more stuff
    Name2; I might, have some; puncuated stuff! But it shouldn't matter.
    Name3; 20394)@(#$
    Name4; No newline at the end of this line
    

    Output:

    Create file: Name1  ==> with contents:  Put this stuff in the first place I want it And then put in more stuff
    Create file: Name2  ==> with contents:  I might, have some; puncuated stuff! But it shouldn't matter.
    Create file: Name3  ==> with contents:  20394)@(#$
    Create file: Name4  ==> with contents:  No newline at the end of this line
    

    I hope this helps! Kylie