相关疑难解决方法(0)

如何在sed和awk(和perl)中搜索和替换任意文字字符串

假设我们在文件中有一些任意文字,我们需要用其他文字替换.

通常情况下,我们只需要达到sed(1)或awk(1)并编写如下代码:

sed "s/$target/$replacement/g" file.txt
Run Code Online (Sandbox Code Playgroud)

但是,如果$ target和/或$替换可能包含对sed(1)敏感的字符(如正则表达式),该怎么办?你可以逃脱它们但是假设你不知道它们是什么 - 它们是武断的,好吗?您需要编写代码以逃避所有可能的敏感字符 - 包括'/'分隔符.例如

t=$( echo "$target" | sed 's/\./\\./g; s/\*/\\*/g; s/\[/\\[/g; ...' ) # arghhh!
Run Code Online (Sandbox Code Playgroud)

对于这么简单的问题,这很尴尬.

perl(1)有\ Q ...\E引用,但即便如此也无法应对'/'分隔符$target.

perl -pe "s/\Q$target\E/$replacement/g" file.txt
Run Code Online (Sandbox Code Playgroud)

我刚发布了一个答案!! 所以我真正的问题是,"有没有更好的方法在sed/awk/perl中进行文字替换?"

如果没有,我会留在这里,以防它有用.

bash perl awk sed xxd

2
推荐指数
2
解决办法
486
查看次数

Perl Pack Unpack on Shell Variable

Ultimately my goal is to convert a hexdump of data to the correct floating point value. I have set up my shell script to isolate the individual hex values I need to look at and arrange them in the correct order for a little Endian float conversion.

To simplify everything, I'll bypass the code I have managed to get working, and I'll start with:

rawHex=0x41000000
echo $(perl -e 'print unpack "f", pack "L", $ENV{rawHex}')
Run Code Online (Sandbox Code Playgroud)

When I execute this code, the …

bash shell perl unpack pack

2
推荐指数
1
解决办法
58
查看次数

标签 统计

bash ×2

perl ×2

awk ×1

pack ×1

sed ×1

shell ×1

unpack ×1

xxd ×1