0

Hello I have a CSV file with this random structure

,,,,,VALUE1,,,,,VALUE2,,,, ,,VALUE3,,,VALUE4,,,VALUE5, ,,,,,,,,,,,,,,,,,,, ,,,,,,,VALUE6,,,,VALUE7,, ,,,,,,,,VALUE8,,,,,, 

And I want to output the first and last ocurrence of each line.

in this manner

For first ocurrence

VALUE1 VALUE3 (empty) VALUE6 VALUE8 

for last ocurrence

VALUE2 VALUE5 (empty) VALUE7 VALUE8 

I've searched for hours and didn't find the best way to achieve this.

Thank you very much.

EDIT: Thank you everybody, this ,+ as separator is the key.

1
  • It there data between the , like this a,b,s,VALUE1,d,e or is it just the , there. Commented Dec 28, 2014 at 18:17

5 Answers 5

4

Using awk with custom field separator:

First non-empty field:

awk -F ',+' '{print $2}' file VALUE1 VALUE3 VALUE6 VALUE8 

Last non-empty field:

awk -F ',+' '{print $(NF-1)}' file VALUE2 VALUE5 VALUE7 VALUE8 

Regex pattern ',+' will make 1 or more commas as a field separator.

Sign up to request clarification or add additional context in comments.

Comments

1

Perl is good for this task

perl -F, -lane '@G = grep {$_ ne ""} @F; print $G[0]' file 

The grep command filters out empty fields.
To print the last field, change $G[0] to $G[-1]


With sed:

 sed 's/^,*//; s/,.*//' file # first field sed 's/,*$//; s/.*,//' file # last field 

Comments

0

From this data:

cat file ,,,,,VALUE1,,,,,VALUE2,,,, ,,VALUE3,,,VALUE4,,,VALUE5, ,,,,,,,,,,,,,,,,,,, ,,,,,,,VALUE6,,,,VALUE7,, ,,,,,,,,VALUE8,,,,,, 

First occurrence:

tr ',' ' ' <file | awk '{print $1}' VALUE1 VALUE3 VALUE6 VALUE8 

Last:

tr ',' ' ' <file | awk '{print $NF}' VALUE2 VALUE5 VALUE7 VALUE8 

Comments

0
sed -e "s/,*\([^,]*\).*/\1/" 

should find the first, and

sed -e "s/\(,*\([^,][^,]*\)\)*,*/\2/" 

should find the last.

Comments

0

if you wanr (empty) as part of the output.

first:

sed ' s/,*\([^,]\+\).*/\1/; s/^,*$/(empty)/; ' 

last:

sed ' s/\(^\|.*,\)\([^,]\+\),*/\2/; s/^,*$/(empty)/; ' 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.