Jose Campos
Jose Campos

Reputation: 23

lines in a file with comma

I would like to know how to create a sub file with a number of commas, for example.

123,abc,qwe,ert

123,456,abc,qwe,fgh

I want to create a file .txt with the line that has 4 commas. (123,456,abc,qwe,fgh).

I tried with this.

awk -F\, '{print NF-1}'

But only gives me the number of commas that each line has.

Upvotes: 0

Views: 75

Answers (4)

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

I want to create a file .txt with the line that has 4 commas.

Alternative sed approach:

cat testfile | sed -En 's/^([^,]+,){4}[^,]*$/&/p' > file.txt

Upvotes: 0

James Brown
James Brown

Reputation: 37394

Replace all commas with commas and count the occurrences and compare:

$ awk 'gsub(/,/,",")==4' file
123,456,abc,qwe,fgh

Upvotes: 0

VIPIN KUMAR
VIPIN KUMAR

Reputation: 3127

Try this -

awk -F, 'NF==5 {print > "file.txt"}' f

cat file.txt
123,456,abc,qwe,fgh

Upvotes: 0

karakfa
karakfa

Reputation: 67467

four delimiters mean five fields, use as a condition, by default it will print the matching lines...

awk -F, 'NF==5' file

Upvotes: 3

Related Questions