Reputation: 1048
Ubuntu 16.04
Bash 4.4
I want to delete the last nth characters from the nth line. Here is a simple file and the last 4 characters on each line is the number 4.
root@0o0o0o0o0 ~/.ssh # cat remove.txt
00000000004444
55555555555555555555555554444
222222222222222224444
000033334444
111114444
To remove the last 4 characters from each line I can execute sed -i 's/....$//' remove.txt
root@0o0o0o0o0 ~/.ssh # sed -i 's/....$//' remove.txt
root@0o0o0o0o0 ~/.ssh # cat remove.txt
0000000000
5555555555555555555555555
22222222222222222
00003333
11111
But what if I wanted to remove the last 4 characters from the 4th line, removing the 3's so the file would look like this:
0000000000
5555555555555555555555555
22222222222222222
0000
11111
Upvotes: 0
Views: 228
Reputation: 133770
Could you please try following in awk
. Written and tested in GNU awk
.
awk -v line="4" -v nofChar="4" '
{
sub(".{"nofChar"}$","")
}
FNR==line{
sub(".{"nofChar"}$","")
}
1
' Input_file
Detailed explanation:
awk -v line="4" -v nofChar="4" ' ##Starting awk program and setting line variable value, nofChar variable value here.
{
sub(".{"nofChar"}$","") ##Substituting last nofChar number of characters at last of the each line here.
}
FNR==line{ ##Checking if this is same line which OP wants to do 2nd time substitution.
sub(".{"nofChar"}$","") ##Substituting last nofChar number of characters at last of the each line here.
}
1 ##Mentioning 1 will print edited/non-edited line.
' Input_file ##Mentioning Input_file name here.
2nd solution: In case number of characters in all lines are different than specific line then try following. One has to change variable named nofUsualChar
value.
awk -v line="4" -v nofChar="4" -v nofUsualChar="4" '
{
sub(".{"nofUsualChar"}$","")
}
FNR==line{
sub(".{"nofChar"}$","")
}
1
' Input_file
Upvotes: 4
Reputation: 88999
With GNU sed:
sed -i 's/....$//; 4s/....$//' file
4s/....$//
limits search and replace to 4th row.
See: man sed
and info sed
Upvotes: 5