How can I use perl on the command-line to print only lines containing Greek unicode characters? For example, only the second of the following lines

  hullo, world
  χαῖρε, ὦ κόσμε

It should be possible to use \p{Greek} rather than the explicit range (0370-03ff, 1f00-1fff).

Methods without perl are also welcome, but I suspect sed, awk, grep cannot do this?


You could run something along the lines of

perl -C -ne '/\p{Greek}/ and print'

Which encoding are you using? If it's UTF-8, you can do:

perl -CSD -ne 'print if /\p{Greek}/' input_utf8.txt >output_utf8.txt

See the -C switch in perlrun.

If it's another encoding, you can use the open pragma for more detailed control.

For example, to read and write UTF-16-LE:

perl -Mopen=':std,:encoding(UTF-16-LE)' -ne 'print if /\p{Greek}/' input_utf16le.txt >output_utf16le.txt

Or, to read a UTF-16-LE file and output in UTF-8:

perl -Mopen=':encoding(UTF-16-LE)' -CS -ne 'print if /\p{Greek}/' input_utf16le.txt >output_utf8.txt

Or, to read UTF-16-LE and write UTF-16-BE:

perl -Mopen=':std,:encoding(UTF-16-BE),IN,:encoding(UTF-16-LE)' -ne 'print if /\p{Greek}/' input_utf16le.txt >output_utf16be.txt

On these latter two, note that there is a subtle but important distinction between perl ... input.txt >output.txt and perl ... <input.txt >output.txt, since the latter reads from STDIN, while the former opens the file, so it's important to keep in mind which of the streams you're changing the encoding of.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.