grep invert search with context
If the lines are all unique you could grep the lines you want to remove into a file, and then use that file to remove the lines from the original, e.g. grep -C 2 “line I don’t want” < A.txt > B.txt grep -f B.txt A.txt
If the lines are all unique you could grep the lines you want to remove into a file, and then use that file to remove the lines from the original, e.g. grep -C 2 “line I don’t want” < A.txt > B.txt grep -f B.txt A.txt
On OSX sed (BSD) sed requires an extension after -i option. Since it is finding -e afterwards it is adding -e to each input filename. btw you don’t even need -e option here. You can pass an empty extension like this: sed -i ” ‘s/foo/bar/g’ $file Or use .bak for an extension to save original … Read more
I’m not aware of any tool for this, but this one-liner extracts precious_table from my_backup.sql file: sed -n ‘/^COPY precious_table /,/^\\\.$/p’ my_backup.sql
To do it in place, if your sed supports the -i option, you can do: sed -i ‘/^string/d’ input-file
To print all lines after, and including, the first match: $ echo -ne ‘apple\nbanana\ncherry\n’ | sed -ne ‘/banana/,$ p’ banana cherry To print all lines after, and NOT including, the first match: $ echo -ne ‘apple\nbanana\ncherry\n’ | sed -e ‘1,/banana/ d’ cherry Filtering lines when pattern matches between “text=” and “status=” can be done with … Read more
You can either write a sed script file and use: sed -f sed.script file1 … Or you can use (multiple) -e ‘command’ options: sed -e ‘/SysAdmin/i\ Linux Scripting’ -e ‘1,$s/A/a/’ file1 … If you want to append something after a line, then: sed -e ‘234a\ Text to insert after line 234’ file1 …
You could use grep -o then pipe through wc -l: $ echo “123 123 123” | grep -o 123 | wc -l 3
If you’re worried about starting two sed processes in a pipeline for performance reasons, you probably shouldn’t be, it’s still very efficient. But based on your comment that you want to do in-place editing, you can still do that with distinct commands (sed commands rather than invocations of sed itself). You can either use multiple … Read more
Depending on your definition of whitespace, something like: tr -d ‘ \t\n\r\f’ <inputFile >outputFile would do the trick.
Using Parameter Expansion: str=”test1@test2″ echo “${str#*@}” The # character says Remove the smallest prefix of the expansion matching the pattern. The % character means Remove the smallest suffix of the expansion matching the pattern. (So you can do “${str%@*}” to get the “test1” part.) The / character means Remove the smallest and first substring of … Read more