LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Slackware (https://www.linuxquestions.org/questions/slackware-14/)
-   -   Removing line from executing script (https://www.linuxquestions.org/questions/slackware-14/removing-line-from-executing-script-4175477184/)

waddles 09-15-2013 02:15 AM

Removing line from executing script
 
Developing a script which leaves data in the script which runs the command to remove and write a line.
Done this to scripts b4 but am drawing a blank on removal and get an error.
Code:

#!/bin/sh
num=`echo $lin | cut -d":" -f1`
echo line number is: $num
sed '${num}d' $0
##data        234        345        456

Shell returns error: sed: -e expression #1, char 4: extra characters after command
Couldn't find any examples with my search query so needing help.
BTW have use echo statements to validate variables and output.

druuna 09-15-2013 02:23 AM

You are using single quotes instead of double quotes which prevent the shell from expanding the variable:
Code:

sed '${num}d' $0

# should be:

sed "${num}d" $0


waddles 09-15-2013 11:45 PM

Regrets for not listing the entire script correctly here is with echo statements:
Code:

#!/bin/sh
lin=`egrep -n "^##data" $0`
echo $lin
num=`echo $lin | cut -d":" -f1`
echo line number is: $num
sed "${num}d" $0 > $0
##data        234        345        456

Yes this works but the entire script is lost. Need to keep script with the ##data statement removed as will write a new ##data statement into the script's tail, i.e. keeping ##data info with the program that updates it.

saulgoode 09-16-2013 01:17 AM

Code:

sed "${num}d" $0 > $0  #<<-- FAIL!
The stdout redirection will result in $0 being opened as a new file before the command is executed. By the time 'sed' gets executed and accesses the file, it is empty.

druuna 09-16-2013 01:26 AM

Elaborating on saulgoode's answer (which is correct):

If you use a modern sed version (4+) you can use the -i flag to edit the file in-place:
Code:

sed -i "${num}d" $0
If you're using an older sed version:
Code:

sed "${num}d" $0 > /tmp/${0}.tmp
mv /tmp/${0}.tmp $0


pan64 09-16-2013 01:45 AM

that can be solved with a single sed:
sed -i '/^##data/d' <filename>
if I understand it well

waddles 09-16-2013 03:18 AM

druuna & pan64 U have it right! Thanks


All times are GMT -5. The time now is 03:47 AM.