Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to remove last comma from line in bash using "sed or awk"

Tags:

bash

sed

awk

Hi I want to remove last comma from a line. For example:

Input:

This,is,a,test

Desired Output:

This,is,a test

I am able to remove last comma if its also the last character of the string using below command: (However this is not I want)

echo "This,is,a,test," |sed 's/,$//'
This,is,a,test

Same command does not work if there are more characters past last comma in line.

echo "This,is,a,test" |sed 's/,$//'
This,is,a,test

I am able to achieve the results using dirty way by calling multiple commands, any alternative to achieve the same using awk or sed regex ?(This is I want)

echo "This,is,a,test" |rev |sed 's/,/ /' |rev
This,is,a test
like image 694
P.... Avatar asked Sep 02 '16 06:09

P....


1 Answers

$ echo "This,is,a,test" | sed 's/\(.*\),/\1 /'
This,is,a test

$ echo "This,is,a,test" | perl -pe 's/.*\K,/ /'
This,is,a test

In both cases, .* will match as much as possible, so only the last comma will be changed.

like image 84
Sundeep Avatar answered Oct 14 '22 07:10

Sundeep