2

Trying to print lines with a condition, example -

input example

Hello:world
Hello:worlds:
Hello:world:example

attempt -

awk -F":" print $1 " + " $2 && if($3 != "") { " + " $3 }

so expected output would be

Hello + world
Hello + worlds
Hello + world + example
3
  • 1
    A little more prose would make sense. Commented Aug 31, 2019 at 17:54
  • Is it only the 3rd field that could possibly be empty, or do you want to delete all empty fields? Commented Aug 31, 2019 at 17:55
  • 1
    You have other issues with your code but the big, glaring one is: tools that interpret scripts (awk, sed perl, rub, etc.) require you to provide the scribt within quotes (single or double) or in a file or some other clearly delimited way. You can't just write awk script, you have to write awk 'script' or awk -f scriptfile. Commented Sep 1, 2019 at 12:55

2 Answers 2

6

If you only have to care about an empty last field, then using sed would be shorter:

$ sed 's/:$//; s/:/ + /g' file
Hello + world
Hello + worlds
Hello + world + example

Your attempted awk command can be salvaged like this:

$ awk -F":" '{ print $1 " + " $2 ($3 != "" ? " + " $3 : "") }' file
Hello + world
Hello + worlds
Hello + world + example

Or, by using OFS (the output field delimiter):

$ awk -F":" -v OFS=' + ' '{ print $1, $2 ($3 != "" ? OFS $3 : "") }' file
Hello + world
Hello + worlds
Hello + world + example

Additionally getting rid of the negative test:

$ awk -F":" -v OFS=' + ' '{ print $1, $2 ($3 == "" ? "" : OFS $3 ) }' file
Hello + world
Hello + worlds
Hello + world + example
0
5

If last column is empty, remove last column from output. $1=$1 forces awk to recreate the row with the output field separator (OFS).

awk '$NF=="" {NF--} {$1=$1}1' FS=':' OFS=' + ' file

Output:

Hello + world
Hello + worlds
Hello + world + example

See: 8 Powerful Awk Built-in Variables – FS, OFS, RS, ORS, NR, NF, FILENAME, FNR

2
  • 1
    Note that the effect of decrementing NF is undefined in the POSIX standard. It may work in some implementations of awk. Commented Aug 31, 2019 at 18:38
  • @Kusalananda: Thank you for pointing that out. I used GNU awk. Commented Sep 2, 2019 at 1:13

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.