How can I remove the last character of a file in unix?
A simpler approach (outputs to stdout, doesn't update the input file):
sed '$ s/.$//' somefile
$
is a Sed address that matches the last input line only, thus causing the following function call (s/.$//
) to be executed on the last line only.s/.$//
replaces the last character on the (in this case last) line with an empty string; i.e., effectively removes the last char. (before the newline) on the line..
matches any character on the line, and following it with$
anchors the match to the end of the line; note how the use of$
in this regular expression is conceptually related, but technically distinct from the previous use of$
as a Sed address.Example with stdin input (assumes Bash, Ksh, or Zsh):
$ sed '$ s/.$//' <<< $'line one\nline two'
line one
line tw
To update the input file too (do not use if the input file is a symlink):
sed -i '$ s/.$//' somefile
Note:
- On macOS, you'd have to use
-i ''
instead of just-i
; for an overview of the pitfalls associated with-i
, see the bottom half of this answer. - If you need to process very large input files and/or performance / disk usage are a concern and you're using GNU utilities (Linux), see ImHere's helpful answer.
How to remove the last characters of each line in a file?
Open your file with open("fileName.ext") method and then iterate each line. on each line you can perform the slicing function [:]
eachLineData = 'username1:password1:dd/mm/yy'
expectedResult = eachLineData[:-9]
print(expectedResult)
Full Code Example:
# Using readlines()
file1 = open('myfile.txt', 'r')
Lines = file1.readlines()
for line in Lines:
expectedResult = line[:-9]
print(expectedResult)
Delete last character from line that contains specific word
This would do it:
sed '/in_bytes/ s/,$//'
Where /in_bytes/
is a search pattern ensuring only matching lines will execute the following command s/,$//
, which is a standard substitution to remove a trailing comma.
Example: https://ideone.com/3hEXBY
Remove last character from a file in unix
quick and dirty
sed 's/.$//' YourFile
a bit secure
sed 's/[|]$//' YourFile
allowing space
sed 's/[|][[:space:]]*$//' YourFile
same for only last char of last line (thansk @amelie for this comment) :
add a $
in front so on quick and dirty it gives sed '$ s/.$//' YourFile
Remove last character of previous line under condition
Using sed
Using GNU sed:
$ sed -z 's/&\n AA/\n AA/g' file
F = 2 * 3 * a * b * 7&
& * 3 * b * c
AA = ...
To keep this command simple, we use the -z
option to read in the whole file at once. (Technically, -z
reads in NUL-separated input. Since no valid Fortran file contains a NUL, this has the effect of reading in the whole file.)
s/&\n AA/\n AA/g
does the substitution that we want. Any place where the file contains &
followed by newline followed by space followed by AA
, this substitution removes the &
.
Reading the whole file in at once is not a good approach if the file is too big to fit in memory. This should not be a problem for Fortran files.
For non-GNU sed (BSD, OSX), we need to add code to replace the -z
flag:
sed 'H;1h;$!d;x; s/&\n AA/\n AA/g' file
Using awk
$ awk '{if (/^ AA/) sub(/[&]$/, "", last); if (NR>1) print last; last=$0} END{print last}' file
F = 2 * 3 * a * b * 7&
& * 3 * b * c
AA = ...
How it works:
This script uses one variable last
which contains the contents of the previous line. If the current line starts with AA
, then we remove, if present, the final &
from last
. In more detail:
if (/^ AA/) sub(/&$/, "", last)
If the current line starts with
AA
, then remove the final&
from the previous line.if (NR>1) print last
If we are not on the first line, then print the previous line.
last=$0
Save the current line as
last
.END{print last}
After we reach the end of the file, print
last
.
Changing files in-place
With GNU sed:
sed -zi.bak 's/&\n AA/\n AA/g' file
With other sed:
sed -i.bak 'H;1h;$!d;x; s/&\n AA/\n AA/g' file
With recent GNU awk:
awk -i inplace '{if (/^ AA/) sub(/&$/, "", last); if (NR>1) print last; last=$0} END{print last}' file
With older awk or non-GNU awk:
awk '{if (/^ AA/) sub(/&$/, "", last); if (NR>1) print last; last=$0} END{print last}' file >file.tmp && mv file.tmp file
How to efficiently remove last line in a file and append new text for large file?
For this code below, the routine is pretty simple since you already know that the last character in your file is a ]. Thus, all you have to do is read the last character of a file and if it is the char ] then you got that file. If that happens, you truncate the last byte from the file and append text to that file. Then you add the char ] to preserve the format. Note that this is for ASCII encoding if your last char is something else that is bigger than a byte then you would have to fix the code a little bit.
using System;
using System.IO;
using System.Text;
public class FSSeek
{
public static void Main()
{
string fileName = "test.txt";
char lastChar = ']';
string toBeAppend = "d\ne\n";
using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.ReadWrite))
{
fs.Seek(-1, SeekOrigin.End);
if ( Convert.ToChar(fs.ReadByte()) == lastChar ){
fs.SetLength(fs.Length - 1);
fs.Write(Encoding.ASCII.GetBytes(toBeAppend));
fs.WriteByte(Convert.ToByte(lastChar));
}
}
}
}
test.txt content:
[
a
b
c
]
How to remove last character of Nth line linux
A simple solution using wc
to count lines and sed
to do the editing:
sed "$(( $(wc -l <file) - 2))s/,$//" file
That will output the edited file on stdout; you can edit inplace with sed -i
.
Related Topics
How to Capitalize First Letter of Each Line in Bash
Getting File Create Notifications for Cifs Mount in Linux
How to Install Visual Studio 2015 in Ubuntu
Configure Options for Building Mingw-64 on Linux-64 for Linux-64 (Ultimately Targetting Windows-64)
How to Schedule an R Script Cronjob in a Linux Server
Linux: Instantiate from User-Space:Eeprom New_Device
Provide Password Using Shell Script
Making 'Long' 4 Bytes in Gcc on a 64-Bit Linux MAChine
How to Change Alignment of Code Segment in Elf
Cannot Open Libmpfr.So.4 After Update on Ubuntu 18.04
Intellij Idea 2017.2 Can't Add Openjk 9 on Linux Mint 18
How to Search for Invisible Control Characters
How to Cross Compile R Packages for MACos from a Linux Environment
Communicating Between a Parent and Its Children
Use Sed to Delete Certain Lines Using an Index with the Line Numbers to Delete