Home > Net >  perl to modify clipboard before pasting
perl to modify clipboard before pasting

Time:09-17

Every time I copy some text in the Kindle app, the content copied is always appended with something extra like (Kindle Location 155). Icon Books. Kindle Edition. and blank lines.

I want to remove these irrelevant information before pasting it somewhere else. e.g. Here's one of the possible input from clipboard mimicking the copying result from Kindle app (mind the space character at the end of the Kindle Edition.):

without

Mark Forsyth. The Etymologicon (Kindle Location 4047). Icon Books. Kindle Edition. 

The expected output to clipboard should be just (blank lines should also be removed):

without

I've searched and tried something like this one using grep, and it works: pbpaste | grep -v -e'Kindle Edition. $' -e '^\s $' | pbcopy

In perl, is there something similar to achieve the same thing? like this:

pbpaste | perl -Mutf8::all -E’$_ =~ s/Kindle Edition. $|^\s $//mg; print $_' | pbcopy

This one doesn't seem to work.

CodePudding user response:

You don't read anything. Your patterns has errors. And it looks like you're trying to remove stuff no matter where it is in the file instead of just at the end.

-n (implied by -p) reads the input a line at a time, executing the program for each line. But the simplest way to delete matches only if they are at the end of the file is to read the entire input at once. -0777 will define a line to be the entire file, so we'll use that.

pbpaste | perl -0777pe's/^\n.* Kindle Edition\.\s*\z//mg' | pbcopy

Test:

$ cat a; echo END
foo

bar

Mark Forsyth. The Etymologicon (Kindle Location 4047). Icon Books. Kindle Edition.
END

$ perl -0777pe's/^\n.* Kindle Edition\.\s*\z//mg' a; echo END
foo

bar
END
  •  Tags:  
  • perl
  • Related