Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing last two chars from each line in a text file

Tags:

linux

How do I remove the last two chars from each line in a text file using just Linux commands?

Also my file seems to have weird ^A delimiters in it. What char does ^A correspond to?

like image 400
syker Avatar asked Apr 08 '10 03:04

syker


People also ask

How do I remove the last character from a file?

Using the truncate Command. The command truncate contracts or expands a file to a given size. The truncate command with option -s -1 reduces the size of the file by one by removing the last character s from the end of the file. The command truncate takes very little time, even for processing large files.

How do you remove the last two characters of a shell?

Removing the last n characters To remove the last n characters of a string, we can use the parameter expansion syntax ${str::-n} in the Bash shell. -n is the number of characters we need to remove from the end of a string.

How can I remove last character from a string in Unix?

You can also use the sed command to remove the characters from the strings. In this method, the string is piped with the sed command and the regular expression is used to remove the last character where the (.) will match the single character and the $ matches any character present at the end of the string.


2 Answers

sed 's/..$//' filename.txt
like image 171
BenV Avatar answered Oct 05 '22 17:10

BenV


Second BenV's answer. However you can make sure that you only remove ^A by:

sed 's/^A^A$//' <file>

In addition to that, to find out what ^A is, I did the following:

% echo -n '^A' |od -x
0000000 0001
0000001

% ascii 0x01
ASCII 0/1 is decimal 001, hex 01, octal 001, bits 00000001: called ^A, SOH
Official name: Start Of Heading

(wanted to add as a comment but it doesn't do quoting properly)

like image 30
Lester Cheung Avatar answered Oct 05 '22 19:10

Lester Cheung