How to to delete a line given with a variable in sed?

后端 未结 3 848
傲寒
傲寒 2021-01-18 06:57

I am attempting to use sed to delete a line, read from user input, from a file whose name is stored in a variable. Right now all sed does is print

相关标签:
3条回答
  • 2021-01-18 06:58

    You might have success with grep instead of sed

    read -p "Enter a regex to remove lines: " filter
    grep -v "$filter" "$file"
    

    Storing in-place is a little more work:

    tmp=$(mktemp)
    grep -v "$filter" "$file" > "$tmp" && mv "$tmp" "$file"
    

    or, with sponge

    grep -v "$filter" "$file" | sponge "$file"
    

    Note: try to get out of the habit of using ALLCAPSVARS: one day you'll accidentally use PATH=... and then wonder why your script is broken.

    0 讨论(0)
  • 2021-01-18 07:08

    Please try this :

    sed -i "${DELETELINE}d" $FILE
    
    0 讨论(0)
  • 2021-01-18 07:11

    You need to delimit the search.

    #!/bin/bash
    
    read -r Line
    
    sed "/$Line/d" file
    

    Will delete any line containing the typed input.

    Bear in mind that sed matches on regex though and any special characters will be seen as such.
    For example searching for 1* will actually delete lines containing any number of 1's not an actual 1 and a star.

    Also bear in mind that when the variable expands, it cannot contain the delimiters or the command will break or have unexpexted results.

    For example if "$Line" contained "/hello" then the sed command will fail with sed: -e expression #1, char 4: extra characters after command.

    You can either escape the / in this case or use different delimiters.

    Personally i would use awk for this

    awk -vLine="$Line" '!index($0,Line)' file
    

    Which searches for an exact string and has none of the drawbacks of the sed command.

    0 讨论(0)
提交回复
热议问题