user2472414
user2472414

Reputation: 141

Remove everything have the 'nth' comma in linux

I will be honest that there are some similar questions on here, where I do not know how to interpret the answer. Any help would be appreciated. I have a string like this:

340,A,T,A,A,T,T,A,T,T,T,T,T,A,A,A,A

And I want to remove everything after the nth comma, in this example it could be the 5th comma though in reality it will be the 170th.

I tried this:

sed -i.back 's/,.*170//'

and this:

's/((?:[^,],){170}).((\s+\S+).*){1,}/$1/g' 

Though clearly I don't know what I'm doing as the first reproduces the entire original file and the second generates no output.

Upvotes: 2

Views: 998

Answers (3)

potong
potong

Reputation: 58478

This might work for you (GNU sed);

sed 's/,/&\n/5;P;d' file

Insert a newline after the nth , print the first line in the pattern space and then delete everything else.

Upvotes: 0

Sniggerfardimungus
Sniggerfardimungus

Reputation: 11782

Simplicity itself: (Note that the comma at the end is required.)

cut -f1-170 -d,

Upvotes: 4

anubhava
anubhava

Reputation: 785621

Using awk you can do this:

s='340,A,T,A,A,T,T,A,T,T,T,T,T,A,A,A,A'
awk -v n=5 'BEGIN{FS=OFS=","} {NF=n+1; $(n+1)=""} 1' <<< "$s"

340,A,T,A,A,

Or using sed:

sed -E 's/^(([^,]*,){5}).*/\1/' <<< "$s"

340,A,T,A,A,

Upvotes: 3

Related Questions