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?
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.
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.
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.
sed 's/..$//' filename.txt
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With