Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

SED Command - remove last comma from a file

Status
Not open for further replies.

simpson

MIS
Oct 23, 2001
58
CA
I am looking for sed command to remove the last comma from a given file. regardless of what line or position.

Any help would be greatly appreciated.
Simpson
 
Hi

Do not cross-post. We hate to read the same question in multiple forums.
[ul]
[li]Show us some sample input.[/li]
[li]Show us the matching desired output.[/li]
[li]Tell us why you want/need to use [tt]sed[/tt].[/li]
[/ul]


Feherke.
 
sorry for the x-post. won't happen again.

-----Input----
"tcp:120.248.242.61:2059,tcp:120.62.243.23:2061" },
"/KM/PAM_GET_CONFIG/destinationServer" = { REPLACE = "148.98.252.101 3181 patrol HEB3C9F9T3A903CEDB6AE9862F05BCE7AE7AA76" },
~
-----Output----
"tcp:xxx.yyy.242.61:2059,tcp:xxx.yyy.243.23:pppp" },
"/KM/PAM_GET_CONFIG/destinationServer" = { REPLACE = "xxx.yyy.252.101 pppp patrol HEB3C9F9T3A903CEDB6AE9862F05BCE7AE7AA76" }
~

Does not have to be SED, that is what I have been trying to get working.
The last comma could be anywhere on the line and is not guaranteed to be the last line in the file.

Thanks!
 
Hi

For your sample text [tt]sed[/tt] would be fine :
Code:
sed '$s/,$//' /input/file
But as soon as the "not guaranteed to be the last line in the file" condition appears, I would not use [tt]sed[/tt] for this. Using [tt]awk[/tt] sounds like a better approach :
Code:
awk '/,/{for(i=1;i<=n;i++)print s[i];n=0}{s[++n]=$0}END{p=1;while(i=index(substr(s[1],p),","))p+=i;s[1]=substr(s[1],1,p-2)substr(s[1],p);for(i=1;i<=n;i++)print s[i]}' /input/file
Teste with [tt]gawk[/tt] and [tt]mawk[/tt].

Feherke.
 
Or Perl:

Code:
perl -pe 'BEGIN { $/=""; } { s/,([^,]*)$/$1/gs; }' /input/file

Annihilannic.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top