【问题标题】:shell script to replace space in 2nd column after delimiter in same file用于在同一文件中的分隔符后替换第二列中的空格的 shell 脚本
【发布时间】:2022-08-18 17:51:05
【问题描述】:

我在linux中有一个包含以下内容的文件:

servername: tesing1001

os: Unix

bu:

aid: 132

location: anywhere

environment: dev-stg

application: ABCD testing space

city: kk

我想用以下数据替换同一文件中的内容:

servername: tesing1001

 os: Unix

**bu: BLANK**  **>>>>here since value is empty i will set it as BLANK hardcoded**

aid: 132

location: anywhere

environment: dev-stg

**application: ABCD_testing_space**  **>>>>>here we will replace string space with \"_\"**

city: kk

我们将在同一个文件中完成所有这些事情。所以,到目前为止,我正试图通过以下逻辑实现上述输出

    #!/bin/bash
    cp -p /opsunix/dyfacter.txt /tmp/customized.txt.tmp
    awk -F \":\" \'{
                 if ($2 == \"\")
                  {
                    print $0  \" blank\"
                  } else {
                      print $0
                        } 
                }\' /opsunix/dyfacter.txt > /tmp/customized.txt.tmp && mv /tmp/customized.txt.tmp /opsunix/dyfacter.txt

借助上述代码,我能够识别空值并将其替换为\“空白的\”细绳。

servername: tesing1001

 os: Unix

**bu: blank**  **>>>>done**

aid: 132

location: anywhere

environment: dev-stg

**application: ABCD testing space**  **>>>>>still need to correct**

city: kk

但是倒数第二行,即:应用:ABCD测试空间我无法将其转换为应用程序:ABCD_testing_space.

应用 sed -i \'s/ /_/g\' /opsunix/dyfacter.txt 正在替换文件中的所有空格 : 。

目的是替换字符串中的空格。

请帮忙!

    标签: linux shell awk sed


    【解决方案1】:

    也许这会对你有所帮助。 我用 _ 替换所有空格 之后,我将所有“:_”替换为“:”

    foo=${str// /_}
    echo $foo
    echo ${foo/:_/: }
    

    【讨论】:

      【解决方案2】:

      使用sed,这会将所有空值更改为BLANK,并在值之间有连续空格的字符串将分隔符:之后的空格更改为_

      $ sed -E ':a;s/^([^ ]*: +)([^ ]*) +/\1\2_/;ta;s/: +?$/: BLANK/' input_file
      servername: tesing1001
      
      os: Unix
      
      bu: BLANK
      
      aid: 132
      
      location: anywhere
      
      environment: dev-stg
      
      application: ABCD_testing_space
      
      city: kk
      

      【讨论】:

        猜你喜欢
        • 2014-12-14
        • 1970-01-01
        • 1970-01-01
        • 2015-09-01
        • 1970-01-01
        • 1970-01-01
        • 2017-05-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多