remove last comma in the file

sunshine737
sunshine737 used Ask the Experts™
on
i have a file with the following

file.txt
a,b,c,d,e

I need to remove last comma in the file

can someone tell the command,which i can use?

Thanks
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
ozo
Most Valuable Expert 2014
Top Expert 2015

Commented:
If there's only one line in the file
sed -i .bak 's/\(.*\),/\1/' file.txt
if there are more lines in the file, do all the lines contain a comma?
does the last line in the file contain a comma?

Author

Commented:
file has only one line.
i just need to delete last comma.
ozo
Most Valuable Expert 2014
Top Expert 2015

Commented:
then the above should work
if there are more lines, it will delete the last comma on every line,
(among them the last comma in the file, but may also include other commas)

Author

Commented:
when i try the sed command, its says

sed: Not a recognized flag: i
Usage:  sed [-n] Script [File ...]
        sed [-n] [-e Script] ... [-f Script_file] ... [File ...]
Most Valuable Expert 2014
Top Expert 2015
Commented:
if your version of sed does not have the -i flag, you can use
sed  's/\(.*\),/\1/' file.txt > file.new
mv file.new file.txt
or
perl -i.bak -pe 's/(.*),/$1/' file.txt

Author

Commented:
Command works perfectly.
if possible could you please explain the command  sed  's/\(.*\),/\1/'

Thanks

Commented:
sunshine737 wrote:
> could you please explain the command  sed  's/\(.*\),/\1/'

\(.*\)   is a grouping that contains the matching characters to the regex .* (all chars), except for the last comma

\1 is a backreference to the characters matched by the above regex

for some more info, check http://sed.sourceforge.net/sedfaq3.html, section 3.1.2

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial