【问题标题】:Awk printing each line in file seperatlyawk 分别打印文件中的每一行
【发布时间】:2021-06-30 22:47:18
【问题描述】:

我正在制作一个脚本,它获取区域记录和值的列表并将其放入 DNS 服务器。 所需输出的格式仅用于 ansible,问题是我无法使用 awk 单独对每一行进行操作。 它的作用是当我没有提到NR 时,它会在同一行中打印所有项目。 当我提到NR 时,它不打印任何内容或仅打印指定的 NR(即仅当我执行 NR==1 时才会打印第一行) 我的目标是迭代所有行并以我想要的格式在行尾后用换行符打印它们。

bash_script

#! /bin/bash

read -p "File: " file
zone=`awk 'NR==1 { print $2}' ${file}`
echo "${zone}:" >> /etc/ansible/roles/create_dns/defaults/main/${zone}.yml

lines=`wc -l < ${file}`
for line_num in $(seq 1 $lines)
do
        echo $line_num
        echo `awk 'NR==$line_num {print "  - { zone: \x27" $2"\x27, record: \x27" $1"\x27, value: \x27" $3"\x27 }\\n"}' ${file}` >> /etc/ansible/roles/create_dns/defaults/main/${zone}.yml
done

$file

ansible ben.com 10.0.0.10
test ben.com 10.0.0.110
example ben.com 10.0.0.120

Wanted output:

ben.com:
  - { zone: 'ben.com', record: 'ansible', value: '10.0.0.10' }
  - { zone: 'ben.com', record: 'test', value: '10.0.0.110' }
  - { zone: 'ben.com', record: 'example', value: '10.0.0.120' }

Output i get:

ben.com:



【问题讨论】:

标签: awk ansible dns


【解决方案1】:

您可以为此使用这个awk

read -p "File: " file
awk '{printf "\t- { zone: \047%s\047, record: \047%s\047, value: \047%s\047 }\n", $2, $1, $3 > $2}' "$file"
cat ben.com

   - { zone: 'ben.com', record: 'ansible', value: '10.0.0.10' }
   - { zone: 'ben.com', record: 'test', value: '10.0.0.110' }
   - { zone: 'ben.com', record: 'example', value: '10.0.0.120' }```

【讨论】:

    【解决方案2】:

    使用您显示的示例,请尝试以下解决方案。这是一个通用的解决方案,在此基础上,您可以在该程序的 split 部分下的 BEGIN 部分中给出多个列名,但这是考虑到您要添加字符串(例如:区域、记录等)在每个字段/列值之前。如果您的字符串数少于 Input_file 中的字段/列数,那么您也可以根据需要从 i

    read -p "File: " file
    awk -v s1='\047' 'BEGIN{OFS=", ";split("zone:,record:,value:",headings,",")} {for(i=1;i<=NF;i++){$i=headings[i]" " s1 $i s1};$0="  - { " $0" }"} 1' "$file"
    

    在此处添加非单行形式的解决方案:

    awk -v s1="'" '
    BEGIN{
      OFS=", "
      split("zone:,record:,value:",headings,",")
    }
    {
      for(i=1;i<=NF;i++){
        $i=headings[i]" " s1 $i s1
      }
      $0="  - { " $0" }"
    }
    1
    ' "$file"
    

    【讨论】:

      猜你喜欢
      • 2013-08-23
      • 2015-02-11
      • 1970-01-01
      • 2015-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-10
      • 1970-01-01
      相关资源
      最近更新 更多