Wrapping an if statement around each line in the file

122 views Asked by At

I have a file containing the next lines:

copy THIS:0022 to UNB:0022;
copy THIS:0023 to UNB:0023;
copy THIS:0024 to UNB:0024;

I would like to process each line and create an if statement around it, like:

if THIS:0022 != ""
    copy THIS:0022 to UNB:0022;
endif
if THIS:0023 != ""
    copy THIS:0023 to UNB:0023;
endif
if THIS:0024 != ""
    copy THIS:0024 to UNB:0024;
endif

How can this be done using bash and awk (and/or sed)?

4

There are 4 answers

0
John Zwinck On BEST ANSWER
#!/bin/bash

while read a b c d; do
    echo "if $b != \"\""
    echo "    $a $b $c $d"
    echo "endif"
done

Put it in foo.sh and run ./foo.sh < infile.

0
Kevin On

One line in sed:

sed -rne 's/(copy THIS:([0-9]{4}).*)/if THIS:\2 != "" \n  \0;\nendif;/p' copy.txt

The parentheses store the original matched value. \0 stores the match from the outer (), which is the whole line in this case \2 stores the match from the inner (), which is the number after 'THIS:'

0
Jotne On

Try this:

awk '{print "if "$2" != \"\"\n    "$0"\nendif"}' file
if THIS:0022 != ""
    copy THIS:0022 to UNB:0022;
endif
if THIS:0023 != ""
    copy THIS:0023 to UNB:0023;
endif
if THIS:0024 != ""
    copy THIS:0024 to UNB:0024;
endif
0
NeronLeVelu On
sed 's/copy \(.*\) to.*/if \1 != ""\
    &\
endif/' YourFile

assuming that your file is in the same pattern (THIS.... and UNB.... are same format and not just sample in place of more traditionnal name)