Find every alternate word in a csv

Hi,

This should be really simple. But not sure why I am unable to crack it.
I am looking for a simple one liner to print every alternate word in a csv. say my file is having content :

abc,def,ghi,jkl,.....

i need the output as below

abc
ghi

Any attempts from your side?

#!/bin/bash

while IFS=',' read -r f1 f2 f3 f4 f5 f6 f7
do
  echo "$f1
 $f3
 $f5
 $f7"
done < "sample.txt"

But its a huge csv and this is not the right solution

Try

awk -F, '{ for (i=1;i<=NF;i+=2) print $i }' file
1 Like

Alternatively with mawk or gawk :

awk 'NR%2' RS='[,\n]'

Note that this will produce a different result, depending on the number of fields per line and the number of lines, which may or may not be what you are looking for with "every alternate word" (is that per line or per file?) (For a single line or if there is always an even number of fields per line, there will be no difference).

for example:

$ echo "1,2,3,4,5
a,b,c,d,e" | mawk NR%2 RS='[,\n]'
1
3
5
b
d

Junior Helper's solution:

$ echo "1,2,3,4,5
a,b,c,d,e" | awk -F, '{ for (i=1;i<=NF;i+=2) print $i }'
1
3
5
a
c
e

Probably you are looking for Junior Helper's suggestion but this may be of interest for somebody else looking at this thread..

1 Like

This may not be very elegant but with sed and awk

echo "abc,def,ghi,jkl" | sed 'y/,/\n/;' | awk 'NR%2==1'

sed (GNU sed) 4.2.2
GNU Awk 4.1.1

1 Like

Thanks so much for taking the time to help me.

$
$ echo "a,b,c,d,e,f,g,h,i,j,k" | perl -lne 'while(/([^,]+)/g){$x//1 ? do{print $1; $x=0}:{$x=1}}'
a
c
e
g
i
k
$
$