简体   繁体   中英

how to remove last comma from line in bash using "sed or 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
$ 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.

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

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

In Gnu AWK too since tagged:

$ echo This,is,a,test|awk '$0=gensub(/^(.*),/,"\\1 ","g",$0)'
This,is,a test

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

$ s="This,is,a,test"
$ echo "${s%,*} ${s##*,}"
This,is,a test

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM