经常使用perl来代替一行的sed awk,主要是想使用perl更强大的正则:
ruby也提供了和perl一样强大的一行代码功能:
[quote]
$ruby --help
-a autosplit mode with -n or -p (splits $_ into $F)
-l enable line ending processing
-n assume 'while gets(); ... end' loop around your script
-p assume loop like -n but print line also like sed
-l automatic call to .chomp on input
[/quote]
上面几个选项经常在一行代码中使用:
echo "Hello 123 world" | perl -ne 's/\s+\d+\s+/,/g;print'
ruby也提供了和perl一样强大的一行代码功能:
[quote]
$ruby --help
-a autosplit mode with -n or -p (splits $_ into $F)
-l enable line ending processing
-n assume 'while gets(); ... end' loop around your script
-p assume loop like -n but print line also like sed
-l automatic call to .chomp on input
[/quote]
上面几个选项经常在一行代码中使用:
echo "Hello 123 world" | ruby -ne 'puts $_.gsub(/\s+\d+\s+/,",")'
#print with line number
ruby -ne 'print($., ": ", $_)' < /etc/irbrc
# Print each line reversed:
ruby -lne 'puts $_.reverse' < /etc/irbrc
# Print the second column from an input
ruby -ane 'puts $F[1]' < /etc/irbrc
# Print lines that contain "eat"
ruby -ne 'puts $_ if /eat/i' < /etc/irbrc
# Same as above:
ruby -pe 'next unless /eat/i' < /etc/irbrc
# Pass-through (like cat, but with possible line-end munging):
ruby -pe '' < /etc/irbrc
# Uppercase all input:
ruby -pe '$_.upcase!' < /etc/irbrc
# Same as above, but actually write to the input file, and make a backup first with extension .bak - Notice that inplace edit REQUIRES input files, not an input STDIN:
ruby -i.bak -p -e '$_.upcase!' /etc/irbrc
本文介绍如何使用Ruby的一行代码功能实现常见的文本处理任务,包括替换字符串、反转行内容、筛选包含特定词汇的行等,这些技巧类似于Perl和sedawk的功能。

被折叠的 条评论
为什么被折叠?



