簡體   English   中英

如何將正則表達式作為參數傳遞給 Bash 腳本中的 Perl one-liner?

[英]How can I pass a regular expression as a parameter to a Perl one-liner in a Bash script?

我有這個input.txt文件:

Dog walks in the park
Man runs in the park
Man walks in the park
Dog runs in the park
Dog stays still
They run in the park
Woman runs in the park

我想搜索runs?匹配項runs? 正則表達式並將它們輸出到文件中,同時在匹配的兩邊用兩個星號突出顯示匹配。 所以我想要的輸出是這樣的:

Man **runs** in the park
Dog **runs** in the park
They **run** in the park
Woman **runs** in the park

我想編寫一個函數來作為這個 Perl 單行程序的包裝器(它會做一些其他的事情),然后用一個正則表達式作為它的參數來調用它。 我寫了以下腳本:

#!/bin/bash

function reg {
    perl -ne 's/($1)/**\1**/&&print' input.txt > regfunctionoutput.txt
}

function rega {
    regex="$1"
    perl -ne 's/($regex)/**\1**/&&print' input.txt > regafunctionoutput.txt
}

perl -ne 's/(runs?)/**\1**/&&print' input.txt > regularoutput.txt
reg 'runs?'
rega 'runs?'

第一個 Perl one-liner 的輸出就是我想要的。 但是當我嘗試將它包裝在一個reg函數中並將表達式作為參數傳遞時,我得到的不是所需的輸出:

****Dog walks in the park
****Man runs in the park
****Man walks in the park
****Dog runs in the park
****Dog stays still
****They run in the park
****Woman runs in the park

我認為問題是$1作為函數參數與 Perl 單行程序中的第一個捕獲組之間存在沖突。 所以我創建了第二個函數rega ,它首先將該表達式分配給一個不同的變量,然后才將它傳遞給 Perl。 但輸出與之前的函數相同。

那么,如何將正則表達式傳遞給函數內部的 Perl one-liner? 我做錯了什么?

您需要使用雙引號"因為shell 不會在單引號中插入變量'這個答案中也很好地解釋了這一點

function reg {
    perl -ne "s/($1)/**\$1**/g&&print" input.pl > regfunctionoutput.txt
}

此外,在 Perl 中,正則表達式捕獲組以$1$2等結尾。 不在\\1 如果你打開警告(在你的單行中使用-w ),你會得到一個\\1 更好地寫成 $1警告。 它在perldiag 中有解釋。

\\%d 最好寫成 $%d

(W 語法)在模式之外,反向引用作為變量存在。 反斜杠的使用在替換的右手邊是祖父的,但在風格上最好使用變量形式,因為其他 Perl 程序員會期待它,如果有超過 9 個反向引用,它會更好地工作。

(W 語法)意味着您可以關閉此警告而no warnings 'syntax';

您可以將$1正則表達式作為命令行參數傳遞,並使用qr//編譯它,因為 Perl 腳本的單引號不會在 shell 下插入,

perl -ne '
  BEGIN{ ($re) = map qr/$_/, shift @ARGV }
  s/($re)/**\1**/ && print
' "$1" input.txt > regfunctionoutput.txt

使用%ENV環境變量:

perl -ne '
  BEGIN{ ($re) = map qr/$_/, $ENV{1} }
  s/($re)/**\1**/ && print
' input.txt > regfunctionoutput.txt

作為旁注,如果您使用-w啟用警告,它會告訴您\\1 is better written as $1s///的替換部分\\1 is better written as $1

暫無
暫無

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

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