Delete a line containing exact pattern in linux [closed]

蹲街弑〆低调 提交于 2020-01-07 07:56:20

问题


I want to delete the lines in test_bash.sh containing the below exact pattern:

export PATH=$PATH:$JAVA_HOME/bin

test_bash.sh

#JAVA PATH
export JAVA_HOME=/data/jdk1.8.0_111
export PATH=$PATH:$JAVA_HOME/bin
export JAVA_OPTS='Xms2048m -Xmx8192m'

#HADOOP PATH
export HADOOP_HOME=/data/hadoop-2.8.5
export PATH=$PATH:$HADOOP_HOME/bin

I want to delete only export PATH=$PATH:$JAVA_HOME/bin

My Script:

if grep -q 'export PATH=$PATH:$JAVA_HOME/bin' /home/admin/Vishal/test_bash.sh ; then
    sed -i "\\#PATH=${PATH}:${JAVA_HOME}//bin#d" /home/admin/Vishal/test_bash.sh
    echo "Deleted"
else
   echo "Nope"
fi

The above script doesnt make any changes to the file.

My Output:

DELETED

UPDATE:

I used single quotes with the grep command instead of double quotes and used $PATH instead of ${PATH}.

The grep is successfully but the sed fails, it doesnt delete the line.


回答1:


There are a lot of overlapping problems here.

Absolutely use single quotes around strings unless you specifically want the shell to expand variables in the string.

Absolutely escape dollar signs and other regex metacharacters if you want them to match literally. Alternatively, you can use grep -F to request literal matching of the text.

Also, I added -x to the grep options to avoid matching in the middle of a longer line.

Your sed command had braces where the grep did not find any, and the slash was doubled. I updated the sed regex to fix these issues.

if grep -q -F -x 'export PATH=$PATH:$JAVA_HOME/bin' /home/admin/Vishal/test_bash.sh ; then
    sed -i '\#PATH=[$]PATH:[$]JAVA_HOME/bin#d' /home/admin/Vishal/test_bash.sh
    echo "Deleted"
else
   echo "Nope"
fi

This is still vaguely speculative; your question is ambiguous or self-contradicting in some places so I have to guess which parts to believe.

Whether to backslash-escape \$ or put the dollar sign in a character class [$] is purely a matter of taste.




回答2:


Try this as a standalone script:

#!/bin/sed -f
/export PATH=$PATH:$JAVA_HOME\/bin/ d


来源:https://stackoverflow.com/questions/59576295/delete-a-line-containing-exact-pattern-in-linux

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!