Link to home
Start Free TrialLog in
Avatar of David Aldridge
David AldridgeFlag for United States of America

asked on

Perl one-liner to remove the last line in a file

I want to ssh to another server and be able to remove the last line from the /etc/sudoers file. I'm NOT very good at one-liners, but I need one here.  Any help would be greatly appreciated!

Thanks!
David
Avatar of Dr. Klahn
Dr. Klahn

On a linux system?  Perl is a bit of overkill - sed can do this fairly simply.

sed '$d' <inputfile> > <outputfile>

Open in new window


The original file will be preserved.  You can then copy the output file back over the input file, or do whatever else is necessary with it.
Avatar of David Aldridge

ASKER

I tried that, but I can't get sed to work on the remote system. Here's the way I ran the command:
ssh myserver "sed '$d' /etc/sudoers /etc/sudoers.rev"   It makes the sudoers.rev, but doesn't remove the last line.
Try this:  Run it without the > and the output file.  Output should go to terminal.  Check to see if it removes the last line.

Note that the last line must be the last line.  No trailing blank lines, no extra empty lines, no CRLF lines.  sed removes the last line, not the last line with something on it.

root@www:# cat test.txt
87.87.232.0/24
16.255.0.0/22
192.168.0.1/30
222.30.0.0/15
84.84.22.0/28
0.0.10.0/24
root@www:# sed '$d' test.txt
87.87.232.0/24
16.255.0.0/22
192.168.0.1/30
222.30.0.0/15
84.84.22.0/28
root@www:# sed '$d' test.txt > test.out
root@www:# cat test.out
87.87.232.0/24
16.255.0.0/22
192.168.0.1/30
222.30.0.0/15
84.84.22.0/28

Open in new window

It's the last line with something on it.  I'm having a little luck with grep -v, but still working on getting it to function through an ssh command.
From home, I will try the command from David Aldridge:
ssh myserver "sed '$d' /etc/sudoers /etc/sudoers.rev"

Open in new window

Try replacing that command to:
/usr/bin/ssh myserver "/bin/sed '$d' /etc/sudoers >/etc/sudoers.rev;/usr/bin/wc -l /etc/sudoers*"

Open in new window

I will try following command at home:
/usr/bin/ssh myserver "if test -f /etc/sudoers.rev;then /usr/bin/wc -l /etc/sudoers.rev;else echo Initially /etc/sudoers.rev file is not present;fi;/bin/sed '$d' /etc/sudoers >/etc/sudoers.rev;/usr/bin/wc -l /etc/sudoers*"

Open in new window

Let us know the output for the same.
Always use full path for any command you are using.
ASKER CERTIFIED SOLUTION
Avatar of MURUGESAN N
MURUGESAN N
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Excellent!