【发布时间】:2019-10-18 11:23:19
【问题描述】:
我在 perl 命令中使用变量时遇到了困难。
我正在尝试将 perl 命令转换为 bash 脚本。 bash 脚本将用于在任何给定文件中搜索给定的正则表达式模式。 bash 脚本应该首先请求打开哪个文件,然后请求正则表达式模式。
我已经有一个可用的命令行,但我尝试将其转换为 bash 脚本的所有操作都不起作用...我对命令行和 bash 脚本没有太多经验,我在互联网上阅读了很多似乎没有任何效果。
#!/bin/bash
read -p "Enter the path to the file : " file_path
read -p "Enter the regular expression : " reg_exp
perl -ln0777e 'my $count=1; print "===================== RESULTS ====================="; while (/'"${reg_exp}"'/g) {printf("[%02d] Offset: 0x%x length: %dB\n Position: %d to %d \n Hex match: %s\n Original: %s\n", $count++, $-[ 0 ], length $1, $-[ 0 ], $-[ 0 ] + length( $1 ) - 1, unpack("H*",$1), $1)}' "${file_path}"
当我尝试在正则表达式中使用变量时,它似乎没有被解释为变量...
结果应该是这样的: enter image description here
我的命令行是这样的:
perl -ln0777e 'my $count=1; print "===================== RESULTS ====================="; while (/REGULAR_EXPRESSION/g) {printf("[%02d] Offset: 0x%x length: %dB\n Position: %d to %d \n Hex match: %s\n Original: %s\n", $count++, $-[ 0 ], length $1, $-[ 0 ], $-[ 0 ] + length( $1 ) - 1, unpack("H*",$1), $1)}' SOURCE_FILE
解决方案:
这是我想出的工作代码。感谢池上的帮助!
#!/bin/bash
read -rp "Enter the path to the file : " file_path
read -rp "Enter the regular expression : " reg_exp
perl -sn0777e'
while (/$reg_exp/g) {
printf "[%1\$02d] Matched %2\$d bytes from position %3\$d (0x%3\$x) to %4\$d (0x%4\$x)\n",
++$count, $+[0]-$-[0], $-[0], $+[0]-1;
printf " Hex: %s\n", unpack("H*", $&);
printf " Match: %s\n", $&;
}
' -- -reg_exp="${reg_exp}" -- "${file_path}"
【问题讨论】:
标签: regex shell perl command-line terminal