4

I have the following table of informations:

ko:K00624  
ko:K20215   
1.5.3.5   
ko:K01106  
2.3.41.5

I want the the output like this:

ko:K00624    
ko:K20215   
-
ko:K01106  
-

I used the following command but it is not working. Please suggest me

cat filename | awk '{if($1!~"ko"); print "-") print }' | less

5 Answers 5

8

A possible corrected version of your awk command:

awk '{if($1!~"ko") print "-"; else print }' filename

although it might be more vernacular to do it like

awk '$0 !~ /^ko/ {$0 = "-"} {print}' filename

or (shorter form)

awk '!/^ko/ {$0 = "-"} 1' filename

Another GNU sed alternative (using the c command rather than the s command):

sed '/^ko/!c-' filename
1
  • 1
    Note that your Sed version is not portable, as POSIX-ly Sed requires a backslash newline after c.
    – Wildcard
    Apr 28, 2017 at 4:19
5
sed -e '/^ko/!s/.*/-/' input_file.dat

meaning, for all lines that do not begin with "ko" , just go ahead and replace the complete line with a dash. For everything else, leave it as it is and print unaltered.

1
  • can you please suggest me with my awk command. it has error Apr 28, 2017 at 2:49
1

Or....

    ~]$ echo -e  "ko:K00624\nko:K20215\n 1.5.3.5\nko:K01106\n2.3.41.5" \
        | while read line ; do if [[ $line =~ ko ]] ; then echo $line ; else echo "-" ; fi ; done
    ko:K00624
    ko:K20215
    -
    ko:K01106
    -
1
1
perl -nE 'say  /(^ko.*)/ ? $1 : "-"'  input.txt
-1

Here is my sed answer, FWIW

sed s/^[^ko].*/-/g filename

You just replace every line that does not begin with ko with a -. (I would have added it as a comment but I don't yet have the rep.)

3
  • [^ko] = not k and not o
    – JJoao
    Apr 28, 2017 at 9:48
  • IOW, that would fail to convert a line like oops or king to -. Apr 28, 2017 at 10:16
  • You also don't need global substitution flag as the start of a line only happens once per line.
    – Aaron
    Apr 28, 2017 at 13:00

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .