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

后端 未结 3 872
傲寒
傲寒 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.

提交回复
热议问题