Issue
I am wondering how I can remove the trailing commas at the first and last row only (still keeping the other commas in there).
I found some similar questions but exactly the same.
Sample input:
000N5,DBS,103151201409220007770001,,,,,,,,,,,,,,,,,,,,,,,,,,,,
10,1256,19700802,,,,SMITH,,ABC,,1,,,,,,GX1 4NL,,
10,1256,19690802,,,,WilliAM,,XX,,1,,,,,,Gl15 4MX,,
101RN5,DBS,103151201409220007770001,,,,,,,,,,,,,,,,,,,,,,,,,,,,
Expected output:
000N5,DBS,103151201409220007770001
10,1256,19700802,,,,SMITH,,ABC,,1,,,,,,GX1 4NL,,
10,1256,19690802,,,,WilliAM,,XX,,1,,,,,,Gl15 4MX,,
101RN5,DBS,103151201409220007770001
Solution
Reasonably easy in sed
;
sed -i~ -e '1!{' -e '$!b' -e } -e 's/,*$//' filename
The braces select lines which are not the first (1!
) and also not the last ($!
) and skip b
to the end of the script. For remaining lines, we proceed into the s/.../.../
which replaces trailing commas with nothing.
The -i~
option says to save the original as a backup in filename~
; if you don't want to keep a backup, pass an empty string (how exactly is slightly platform-dependent; on BSD and MacOS, you need -i ''
whereas on e.g. Linux you can simply omit the ''
).
Answered By - tripleee Answer Checked By - Gilberto Lyons (WPSolving Admin)