Perl Oneliner Program
(Redirected from perl Oneliner Program)
Jump to navigation
Jump to search
A Perl Oneliner Program is a CLI-based Perl program that can be expressed in one line of code.
- Context:
- It can use Perl Interpreter Parameters.
- Example(s):
perl -ne 'chomp;@w=split(/\t/);print "$w[0]\t$w[2]\n"' file.tsv
- Counter-Example(s):
- See: Perl Coding Example, Perl Program Template.
Notes
coding examples of Perl Oneliner Program
- wrap each line with <s> … </s>
% perl -ne 'print “<s>$_<\/s>"' file.txt
- print the first and third column of a tab separated file
% perl -ne 'chomp;@w=split(/\t/);print "$w[0]\t$w[2]\n"' file.tsv
- print the text that follows "artid=" but before a "&"
perl -ne 's/.*?artid=(.*?)[&"].*/$1/;print "$_\n" file.txt
- cut out content that matches a pattern (within < xxx >)
perl -ne 'chomp;s/<\d.+?jpg.+?>g; print "$_\n"' file.txt
simple pattern
perl -pi -e 's/you/me/g' file
a path string within the files under the local directory
% perl -i.bak -p -e "s#/home/george#/home/curious#" `find . -print`
- repeated strings
finding all repeated lines in a file?
perl -ne 'print if $a{$_}++' file
report the count of each repeated string
perl -ne 'while (<>) {chomp; $hash{lc($_)}++}; @sorted = sort { $hash{$a} < $hash{$b} } keys %hash ; foreach (@sorted) {print "$hash{$_} $_\n"}'
perl -ne 'chomp;split;foreach (@_){$hash{lc($_)}++}; @sorted = sort { $hash{$a} < $hash{$b} } keys %hash ; foreach (@sorted) {print "$hash{$_} $_\n"}'
- use a package
use package to sum the numbers in a file
perl -MList::Util=sum -alne 'print sum @F'
Convert non-ASCII characters into SGML/HTML/XML-style decimal numeric character references (e.g. Ş becomes Ş):
perl -C -pe 's/([^\x00-\x7f])/sprintf("&#%d;", ord($1))/ge;'
Convert (hexa)decimal numeric character references to UTF-8:
perl -C -pe 's/&\#(\d+);/chr($1)/ge;s/&\#x([a-fA-F\d]+);/chr(hex($1))/ge;'
Assume one legal JSON record per line
zcat file.json.gz | perl -MLWP::Simple -MJSON -se 'while(<STDIN>) {$ref = decode_json($_); print "$ref->{attrX}\t$ref->{xttrY}\n"}' > out.tsv
- pass a parameter
var=bar
perl -sne 'chomp; print "$_ " . $foo;' -- -foo=${var} file.txt
- replace term from a 2-column dictionary file
cat file.txt | \
perl -sne 'open DICT, “<$dict"; while(<DICT>) {($new,$prev)=split ; $regex{$prev}=$new;} $prevs = join "|", keys %regex ; while (<STDIN>) { s/($prevs)/$regex{$1}/g; print}' \
-- -dict=dict.tsv