Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
How can I delete the last character in a file. I dont care what the character is - all i want to do is delete the last character.
Whats the easiest way to do this?
Any help is appreciated

Hi:
Here's one way:
#!/bin/ksh
nr=$(wc -l filename)nawk '
{ if(NR nn)
print $0
else
{
str=substr($0, 1, length($0)-1)
print str
}
} ' nn="$nr" filenameYou could read the whole file into an array, but I chose to find the number of lines before processing
Regards,
Nails

...though that will only make a difference if the last line of the file contains a character to delete. I'm not sure what you want to happen in that situation though.

Here is what I want..
I have files that contain data in this format
name1,
name2,
name3,I just want to get rid of comma after "name3". Note each file may contain different number of records - also each record maybe of varying length..

Then the sed command should work, i.e:
sed '$s/.$//' filename.dat
or to be safe you could specify a literal comma rather than "any character":
sed '$s/,$//' filename.dat
If the final line of the file doesn't match the pattern it will have no effect, which is what I meant above. In this case it sounds like what you'd want to happen anyway.

This is great - does the job..
Let me try to get more out of this..
Here is the bigger pisture..
I have a file test.dat which contains
Test.dat
--------
This directory contains file.dat which is very useful.I want to get list of files from the current directory and replace the word file.dat with the list of files separated by comma
So if my directory has:
file1.dat
file2.dat
file3.datMy end result of test.dat should be
test.dat
--------
This directory contains file1.dat,file2.dat,file3.dat which is very useful.How can this be done?
The way I think it may work is:
1. awk to get list of files serataed by comma
2. sed to delete last comma
3. perl to search and replaceIs there a better/easier/another way to do it???

There are a lot of ways to go about building the list of comma-delimited filenames. You said the files were in your current directory, and I assume that test.dat is there also. In the following, I went after the fileset file*dat. I use korn shell syntax here.
flist=$(ls file*dat|sed -e '{H;$!d;}' -e 'x;s/\n/,/g;s/^,//')
sed "s/file.dat/$flist/" test.dat > test.new

![]() |
![]() |
![]() |

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |