簡體   English   中英

使用來自 bash 的 stdin 的多行 perl 的 heredoc 語法

[英]heredoc syntax for multi-line perl using stdin from bash

如何將文件傳遞給 perl 腳本進行處理,並對多行 perl 腳本使用 heredoc 語法? 我試過這些,但沒有運氣:

cat ng.input | perl -nae <<EOF
if (@F==2) {print $F[0] . "\t". $F[1] . "\n"} else { print "\t" . $F[0] . "\n" }
EOF

cat ng.input | perl -nae - <<EOF
if (@F==2) {print $F[0] . "\t". $F[1] . "\n"} else { print "\t" . $F[0] . "\n" }
EOF

確實不需要這里的文檔。 您可以簡單地使用多行參數:

perl -nae'
    if (@F==2) {
       print $F[0] . "\t". $F[1] . "\n"
    } else {
       print "\t" . $F[0] . "\n"
    }
' ng.input

清潔,比Barmar的便攜式,並且僅使用一個過程而不是Barmar的三個過程。


請注意,您的代碼可能會縮小為

perl -lane'unshift @F, "" if @F!=2; print "$F[0]\t$F[1]";' ng.input

甚至

perl -pale'unshift @F, "" if @F!=2; $_="$F[0]\t$F[1]";' ng.input

使用流程替代:

cat ng.input | perl -na <(cat <<'EOF'
if (@F==2) {print $F[0] . "\t". $F[1] . "\n"} else { print "\t" . $F[0] . "\n" }
EOF
)

還要在EOF標記EOF加上單引號,以使perl腳本中的$F不會被擴展為shell變量。

也可以將heredoc 作為“-”第一個參數傳遞給perl:

perl -lna - ng.input <<'EOF'
if (@F==2) {print $F[0] . "\t". $F[1] . "\n"} else { print "\t" . $F[0] . "\n" }
EOF

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM