使用gawk和/或sed使用十六进制表示法搜索不可打印的字符

时间:2017-08-07 17:18:03

标签: windows awk sed hex gawk

在Windows命令行中,我试图修复在" |"分隔的某个字段中发生的断行。在某些业务系统中,自由文本字段允许用户输入返回,这些有时会在提取事务时中断记录行。

我有来自UnxUtilsGnuWin的GAWK(GNU Awk 3.1.0)和SED(GNU sed版本4.2.1)。我的数据如下:

some_function1($add['result']);
...
some_function2($add['number1']);

由于第一段中解释的原因,第二行被打破。在第2行的末尾返回是一个常规的Windows返回,在十六进制编辑器中看起来像x0D x0A。

使用sed或gawk而不是/ n或/ r类型表示法删除时,我希望能够使用十六进制值(多于一种情况)来增加灵活性。只有当代码出现在第三列时,代码应该能够替换它。只应使用sed或(x)awk。对于gawk" sed风格"如果可能的话,替换(如使用-i参数)方法会有所帮助。

尝试以下操作但未捕获任何内容:

smith|Login|command line is my friend|2
oliver|Login|I have no idea 
why I am here|10
dennis|Payroll|are we there yet?|100
smith|Time|going to have some fun|200
smith|Logout|here I come|10

也尝试用

替换
gawk -F "|" "$3 ~ /\x0D\x0A/" data.txt

gawk -F "|" "{gsub(/\x0d\x0a/, \x20, $3); print }" OFS="|" data.txt

(能够用sed捕获x20(空格),但没有运气回报)

1 个答案:

答案 0 :(得分:0)

目前还不完全清楚你要做什么(为什么你想用空格char替换行结尾?)但这可能会让你走上正确的道路:

$arr = file('file.txt');

foreach ($arr as $value) {
    if ('' === trim($value)) {
        // line is empty
        continue;
    }

    // process non-empty line here
}

如果您想进行就地编辑,只需预先添加awk -v RS='\r\n' -v ORS=' ' '1' file

这对于就地编辑和多字符RS来说都是gawk。您可能还需要添加-i inplace(也是仅限gawk),具体取决于您运行的平台,以阻止底层C基元在gawk看到它们之前剥离-v BINMODE=3

坚持下去,我看到你正在使用gawk 3.1.0 - 已经过时5年了,升级你的gawk版本以获取最新的错误修复和功能(包括-i inplace)。

挂起2 - 您是否真的尝试使用空白字符替换记录中的换行符?这更简单:

\r

例如(在awk 'BEGIN{RS=ORS="\r\n"} {gsub(/\n/," ")} 1' file 之前添加\s*,因为您的输入具有尾随空格,我假设您也想删除它):

\n

或者在输出中使用UNIX行结尾而不是DOS只是不设置ORS:

$ cat -v file
smith|Login|command line is my friend|2^M
oliver|Login|I have no idea
why I am here|10^M
dennis|Payroll|are we there yet?|100^M
smith|Time|going to have some fun|200^M
smith|Logout|here I come|10^M

$ awk 'BEGIN{RS=ORS="\r\n"} {gsub(/\s*\n/," ")} 1' file | cat -v
smith|Login|command line is my friend|2^M
oliver|Login|I have no idea why I am here|10^M
dennis|Payroll|are we there yet?|100^M
smith|Time|going to have some fun|200^M
smith|Logout|here I come|10^M
相关问题