12

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
P....
  • 17,421
  • 2
  • 32
  • 52
  • Possible duplicate of [Search and replace in bash using regular expressions](http://stackoverflow.com/questions/13043344/search-and-replace-in-bash-using-regular-expressions) – Micha Wiedenmann Sep 02 '16 at 07:43
  • There is no need to spawn a sed, awk, etc. process, since a pure Bash solution exists: http://stackoverflow.com/a/22261454/1671066 – Micha Wiedenmann Sep 02 '16 at 07:44

5 Answers5

15
$ 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.

Sundeep
  • 23,246
  • 2
  • 28
  • 103
6

You can use a regex that matches not-comma, and captures that group, and then restores it in the replacement.

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

Output:

This,is,a test
merlin2011
  • 71,677
  • 44
  • 195
  • 329
5

All the answer are based on regex. Here is a non-regex way to remove last comma:

s='This,is,a,test'
awk 'BEGIN{FS=OFS=","} {$(NF-1)=$(NF-1) " " $NF; NF--} 1' <<< "$s"

This,is,a test
anubhava
  • 761,203
  • 64
  • 569
  • 643
2

In Gnu AWK too since tagged:

$ echo This,is,a,test|awk '$0=gensub(/^(.*),/,"\\1 ","g",$0)'
This,is,a test
James Brown
  • 36,089
  • 7
  • 43
  • 59
1

One way to do this is by using Bash Parameter Expansion.

$ s="This,is,a,test"
$ echo "${s%,*} ${s##*,}"
This,is,a test
John B
  • 3,566
  • 1
  • 16
  • 20