如果条件不满足则删除分隔符并在条件上替换字符串

时间:2015-02-12 21:27:23

标签: shell unix

考虑以下文件。

HEAD~XXXX
XXX~XXX~XXX~XXX~XXX~XXX~~WIN~SCRIPT~~~
XXX~XXX~XXX~XXX~XXX~XXX~~WIN~TPSCRI~~~
XXX~XXX~XXX~XXX~XXX~XXX~~WIN~RSCPIT~~~
TAIL~20

希望输出如下所示:

HEAD~XXXX
XXX~XXX~XXX~XXX~XXX~XXX~~WIN~SCRIPT~~~
XXX~XXX~XXX~XXX~XXX~XXX~~~~~~
XXX~XXX~XXX~XXX~XXX~XXX~~~~~~
TAIL~20

如果第9个字段是SCRIPT,我想要第8个和第8个字段。第9个字段是空的,就像第10个&如果该行包含单词HEAD / TAIL,则必须忽略上述条件,即NF!= 13 - 将需要标题&页脚,因为它在输入中。 我已经尝试了下面的内容,但应该有一个更聪明的方法。

awk -F'~' -v OFS='~' '($9 != "Working line takeover with change of CP" {$9 = ""}) && ($9 != "Working line takeover with change of CP" {$8 = ""}) {NF=13; print}' file

上述不起作用

    head -1 file > head
    tail -1 file > tail
    sed -i '/HDR/d' file
    sed -i '/TLR/d' file
    sed -i '/^\s*$/d' file
    awk -F'~' -v OFS='~' '$9 != "Working line takeover with change of CP" {$9,$8 = ""} {NF=13; print}' file  >>  file.tmp    //syntax error

    cat file.tmp >> head
    cat tail >> head
    echo "" >> head 
    mv head file1

我正在尝试具有以下要求的UNIX shell脚本。

考虑这样的文件..

XXX~XXX~XXX~XXX~XXX~XXX~~XXX~~SCRIPT~~~
XXX~XXX~XXX~XXX~XXX~XXX~~XXX~~OTHERS~~~~
XXX~XXX~XXX~XXX~XXX~XXX~~XXX~~OTHERS~~~
  1. 每个文件应该有12个字段(〜作为分隔符),如果不是〜必须删除。
  2. 如果第10个字段中存在除SCRIPT字符串以外的任何内容,则必须删除该字段。
  3. 我在/ bin / bash中尝试了以下内容,我知道我做得不好。我正在为sed& amp; awk命令。

    while read readline 
        echo "entered while"
        do
            fieldcount=`echo $readline | awk -F '~'  '{print NF}'`
            echo "Field count printed"
            if [ $fieldcount -eq 13 ] && [ $fieldcount -ne 12 ]
            then
            echo "entering IF & before deletion"
                #remove delimiter at the end of line
                #echo "$readline~" >> $S_DIR/$1.tmp
                #sed -i '/^\s*$/d' $readline 
                sed -i s'/.$//' $readline
                echo "after deletion"
                if [ awk '/SCRIPT/' $readline -ne "SCRIPT"]
          then
                #sed -i 's/SCRIPT//' $readline
                replace_what="OTHERS"
                #awk -F '~' -v OFS=~ '{$'$replace_what'=''; print }'
                sed -i 's/[^,]*//' $replace_what
                echo "$readline" >> $S_DIR/$1.tmp
                fi
            else
                echo "$readline" >> $S_DIR/$1.tmp
            fi      
            done < $S_DIR/$1
    

1 个答案:

答案 0 :(得分:1)

awk -F'~' -v OFS='~' '$10 != "SCRIPT" {$10 = ""} {NF=12; print}' file
XXX~XXX~XXX~XXX~XXX~XXX~~XXX~~SCRIPT~~
XXX~XXX~XXX~XXX~XXX~XXX~~XXX~~~~
XXX~XXX~XXX~XXX~XXX~XXX~~XXX~~~~

在bash中,我会写:

(
  # execute in a subshell, so the IFS setting is localized
  IFS='~'
  while read -ra fields; do
    [[ ${fields[9]} != "SCRIPT" ]] && fields[9]=''
    echo "${fields[*]:0:12}"
  done < file
)

您的后续问题:

awk -F'~' -v OFS='~' '
    $1 == "HEAD" || $1 == "TAIL" {print; next}
    $9 != "SCRIPT" {$8 = $9 = ""}
    {NF=13; print}
' file

如果您还有其他问题,请创建一个新问题,而不是编辑此问题。