简体   繁体   English

结合awk和sed以匹配行并替换字符

[英]Combining awk and sed to match line and replace characters

I'm trying to match first letter, in this example "B", and second column "2". 我正在尝试匹配第一个字母(在此示例中为“ B”)和第二列“ 2”。 When match is found replace characters [38-41] with white spaces. 找到匹配项后,请用空格替换字符[38-41]。

Here is the data I'm trying to modify: 这是我要修改的数据:

A1234A123 1 2 12345.12345 1234.1234.112341234

B1234A123 2 2 12345.12345 1234.1234.112341234

A1234A123 2 2 12345.12345 1234.1234.112341234

I can match the conditions with awk using: 我可以使用awk匹配条件:

awk '/^B/ && $2=="2" {print}' 

and I can modify the lines with sed using: 我可以使用sed修改行:

sed -r 's/^(.{37})(.{4})/\1    /' 

I'm trying to find the lines in the file which contains the two conditions and then modify the characters, while still printing the entire line of lines that don't match. 我试图在包含两个条件的文件中查找行,然后修改字符,同时仍打印不匹配的整行。 Can you combine the two commands in order to introduce some sort of if/then statement? 您可以结合使用这两个命令来引入某种if / then语句吗?

I've tried to combine the commands, but it edited all of the lines: 我尝试合并命令,但是它编辑了所有行:

awk '/^B/ && $2=="2" {print}' ¦ sed -r 's/^(.{37})(.{4})/\1    /' data

Resulting data should look like this: 结果数据应如下所示:

A1234A123 1 2 12345.12345 1234.1234.112341234

B1234A123 2 2 12345.12345 1234.1234.1    1234

A1234A123 2 2 12345.12345 1234.1234.112341234

Thanks in advance. 提前致谢。

You can use single awk to combine both commands: 您可以使用单个awk组合这两个命令:

awk '/^B/ && $2=="2"{$0=substr($0, 1, 37) "    " substr($0, 38, 4)} 1' file
A1234A123 1 2 12345.12345 1234.1234.112341234
B1234A123 2 2 12345.12345 1234.1234.1    1234
A1234A123 2 2 12345.12345 1234.1234.112341234

您可以通过在正则表达式前添加sed来指示仅替换匹配行( /^B[^ ]* 2/ ):

sed -r '/^B[^\s]*\s2\s/s/^(.{37}).{4}/\1    /' data

使用GNU awk:

gawk '/^B/ && $2=="2" {print gensub(/(.{37}).{4}/,"\\1    ","")}' data

In Gnu Awk version 4 you could try: 在Gnu Awk版本4中,您可以尝试:

gawk 'BEGIN { FIELDWIDTHS = "1 9 1 26 4 20"; OFS="" }
$1=="B" && $3=="2" {
    $5="    "
} 1' file

with output: 输出:

A1234A123 1 2 12345.12345 1234.1234.112341234
B1234A123 2 2 12345.12345 1234.1234.1    1234
A1234A123 2 2 12345.12345 1234.1234.112341234

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM