简体   繁体   中英

Unable to delete a line in file in shell script

I have to delete a line in a file from inside a shell script.

I am trying this:

linenumber=0
##CHeck If server IP exists
if grep -wq $serverip $FILE; then
        echo "IP exists"
        linenumber=$(awk -v serverip="$serverip" '$0 ~ serverip {print NR}' $FILE)
        echo "$linenumber"
        sed -e '${$linenumber}d' $FILE

fi

Basically I extract the line number and then want to delete it.

sed -e '1d' $FILE  --> WOrks on CLI but inside script does not work

Why? How to get it working ?

This is simply a case of using the incorrect quotes around your sed command, so the variable isn't being used. Ignoring the fact that you're unnecessarily using 3 tools when 1 would suffice, the fix is this:

sed -e "${linenumber}d" "$FILE"

Perhaps your requirement is more complex than it appears but I would suggest changing your entire script to this:

awk -v serverip="$serverip" '!($0 ~ serverip)' "$FILE"

This prints every line that doesn't contain the shell variable $serverip . It is assumed that you have escaped any regex meta-characters present in the variable.

Alternatively (and more succinctly):

sed "/$serverip/d" "$FILE"

If you actually want the messages to be printed out (I assumed that they were for debugging), then that's easy enough to achieve:

awk -v serverip="$serverip" '$0 ~ serverip { print "IP exists"; print NR; next } 1' "$FILE"

If you're not familiar with the 1 at the end, it's just a common shorthand which causes awk to print each line ( 1 is always true and the default action is { print } ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM