在特定字段中使用awk搜索模式并替换其内容

时间:2019-02-27 09:59:33

标签: awk

我需要找到一个带有空格或制表符的空密码字段,并用x替换(在/ etc / passwd文件中)

我在awk中发现了这种语法,该语法向用户显示第二个字段(使用:作为分隔符)在何处或为空,或者在其中包含空格或制表符:

awk -F":" '($2 == "" || $2 == " " || $2 == "\t") {print $0}' $file

结果如下:

user1::53556:100::/home/user1:/bin/bash
user2: :53557:100::/home/user2:/bin/bash
user3:  :53558:100::/home/user3:/bin/bash

我如何对awk说用另一个字符替换第二个字段(空,空格或制表符)? (例如x)

2 个答案:

答案 0 :(得分:0)

请您尝试以下。

awk 'BEGIN{FS=OFS=":"} {$2=$2=="" || $2~/^[[:space:]]+$/?"X":$2} 1' Input_file

说明: :添加了上述代码的说明。

awk '                                          ##Starting awk program here.
BEGIN{                                         ##Starting BEGIN section here which will be executed before Input_file is being read.
  FS=OFS=":"                                   ##Setting FS and OFS as colon here for all lines of Input_file.
}                                              ##Closing BEGIN section block here.
{
  $2=$2=="" || $2~/^[[:space:]]+$/?"X":$2      ##Checking condition if $2(2nd field) of current line is either NULL or having complete space in it then put its vaklue as X or keep $2 value as same as it is.
}
1                                              ##mentioning 1 will print edited/non-edited current line.
' Input_file                                   ##Mentioning Input_file name here.


编辑: 根据OP,OP无需触摸Input_file的最后一行,因此现在添加以下解决方案。

tac Input_file | awk 'BEGIN{FS=OFS=":"} FNR==1{print;next} {$2=$2=="" || $2~/^[[:space:]]+$/?"X":$2} 1' | tac


EDIT2: :如果您希望自己与单身awk亲近,然后尝试遵循。

awk '
BEGIN{
  FS=OFS=":"
}
prev{
  num=split(prev,array,":")
  array[2]=array[2]=="" || array[2]~/^[[:space:]]+$/?"X":array[2]
  for(i=1;i<=num;i++){
    val=(val?val OFS array[i]:array[i])
  }
  print val
  val=""
}
{
  prev=$0
}
END{
  if(prev){
    print prev
  }
}'  Input_file

如果要更改Input_file本身,请在上面的代码中附加> temp_file && mv temp_file Input_file

答案 1 :(得分:0)

$ awk 'BEGIN{FS=OFS=":"} (NF>1) && ($2~/^[[:space:]]*$/){$2="x"} 1' file
user1:x:53556:100::/home/user1:/bin/bash
user2:x:53557:100::/home/user2:/bin/bash
user3:x:53558:100::/home/user3:/bin/bash

要使用GNU awk更改原始文件,

awk -i inplace 'BEGIN{FS=OFS=":"} (NF>1) && ($2~/^[[:space:]]*$/){$2="x"} 1' file

或任何awk:

awk 'BEGIN{FS=OFS=":"} (NF>1) && ($2~/^[[:space:]]*$/){$2="x"} 1' file > tmp && mv tmp file

NF>1的测试可确保我们仅对已经具有至少2个字段的行进行操作,因此当输入中有空行时,我们不会在输出中创建类似于:x的行文件。其余的希望很明显。