Marjer
Marjer

Reputation: 1403

Repeatly replace a delimiter at a given count (4), with another character

Given this line:

12,34,56,47,56,34,56,78,90,12,12,34,45

If the count of the commas(,) is greater than four, replace 4th comma(,) with ||.

If the count is lesser or equal to 4 no need replace the comma(,).

I am able to find the count by the following awk:

awk -F\, '{print NF-1}' text.txt

then I used an if condition to check if the result is greater than 4. But unable to replace 4th comma with ||

Find the count of the delimiter in a line and replace the particular position with another character.

Update:

I want to replace comma with || symbol after every 4th occurrence of the comma. Sorry for the confusion.

Expected output:

12,34,56,47||56,34,56,78||90,12,12,34||45

Upvotes: 1

Views: 78

Answers (5)

ex-bart
ex-bart

Reputation: 1392

$ echo 12,34,56,47,56,34,56,78,90,12,12,34,45 | sed 's/,/||/4'
12,34,56,47||56,34,56,78,90,12,12,34,45
$ echo 12,34,56,47 | sed 's/,/||/4'
12,34,56,47

Should work with any POSIX sed

Update:

For the updated question you can use

$ echo 12,34,56,47,56,34,56,78,90,12,12,34,45 | sed -e 's/\(\([^,]*,\)\{3\}[^,]*\),/\1||/g'
12,34,56,47||56,34,56,78||90,12,12,34||45

Unfortunately, POSIX sed's s command can take either a number or g as a flag, but not both. GNU sed allows the combination, but it does not do what we want in this case. So you have to spell it out in the regular expression.

Upvotes: 3

anubhava
anubhava

Reputation: 786359

Using awk you can do:

s='12,34,56,47,56,34,56,78,90,12,12,34,45'
awk -F, '{for (i=1; i<NF; i++) printf "%s%s", $i, (i%4?FS:"||"); print $i}' <<< "$s"
12,34,56,47||56,34,56,78||90,12,12,34||45

Upvotes: 1

Ed Morton
Ed Morton

Reputation: 204731

With GNU awk for gensub():

$ echo '12,34,56,47,56,34' | awk -F, 'NF>5{$0=gensub(/,/,"||",4)}1'
12,34,56,47||56,34

$ echo '12,34,56,47,56' | awk -F, 'NF>5{$0=gensub(/,/,"||",4)}1'
12,34,56,47,56

Upvotes: 4

Shravan Yadav
Shravan Yadav

Reputation: 1317

with awk

 awk -F, 'NF-1>4{for(i=1;i<NF;i++){if(i==4)k=k$i"||";else k=k$i","} print k$NF}' filename

Upvotes: 0

Kent
Kent

Reputation: 195289

if the count is greater than four i want to replace 4th comma(,) with ||

give this line a try (gnu sed):

sed -r '/([^,]*,){4}.*,/s/,/||/4' file

test:

kent$  echo ",,,,,"|sed -r '/([^,]*,){4}.*,/s/,/||/4'
,,,||,

kent$  echo ",,,,"|sed -r '/([^,]*,){4}.*,/s/,/||/4'    
,,,,

kent$  echo ",,,"|sed -r '/([^,]*,){4}.*,/s/,/||/4'     
,,,

Upvotes: 0

Related Questions