Search code examples
bashcutxargs

xargs and cut: getting `cut` fields of a csv to bash variable


I am using xargs in conjuction with cut but I am unsure how to get the output of cut to a variable which I can pipe to use for further processing.

So, I have a text file like so:

test.txt:

/some/path/to/dir,filename.jpg
/some/path/to/dir2,filename2.jpg
...

I do this:

cat test.txt | xargs -L1 | cut -d, -f 1,2
/some/path/to/dir,filename.jpg

but what Id like to do is:

cat test.txt | xargs -L1 | cut -d, -f 1,2 | echo $1 $2

where $1 and $2 are /some/path/to/dir and filename.jpg

I am stumped that I cannot seem to able to achieve this..


Solution

  • You may want to say something like:

    #!/bin/bash
    
    while IFS=, read -r f1 f2; do
        echo ./mypgm -i "$f1" -o "$f2"
    done < test.txt
    
    • IFS=, read -r f1 f2 reads a line from test.txt one by one, splits the line on a comma, then assigns the variables f1 and f2 to the fields.
    • The line echo .. is for the demonstration purpose. Replace the line with your desired command using $f1 and $f2.