How to add to lines in a file that does not contain a specific template using shell script

I have a flat file as follows:

11|aaa 11|bbb|NO|xxx 11|ccc 11|ddd|NO|yyy 

For strings that do not contain | NO | I would like to add a line | YES | in the end. Therefore, my file should look like this:

 11|aaa|YES| 11|bbb|NO|xxx 11|ccc|YES| 11|ddd|NO|yyy 

I am using AIX, and the sed -i option for inline replacements is not available. Therefore, I am currently using the following code for this:

 #Get the lines that do not contain |NO| LINES=`grep -v "|NO|" file` for i in LINES do sed "/$i/{s/$/|YES|/;}" file > temp mv temp file done 

However, above, since my file contains more than 40,000 lines, it takes about 3 hours. I believe this takes a lot of time because it needs to search every line and write a temporary file. Is there a faster way to achieve this?

+4
source share
3 answers

If temp.txt is your file, try:

 awk '$0 !~ /NO/ {print $0 "|YES|"} $0 ~ /NO/ {print}' temp.txt 
+2
source

It will be fast:

 sed '/NO/!s/$/|YES|/' filename 
+4
source

Simple with awk . Put the code below in the script and run it with awk -f script file > temp

 /\|NO\|/ { print; next; } # just print anything which contains |NO| and read next line { print $0 "|YES|"; } # For any other line (no pattern), print the line + |YES| 

I'm not sure about awk regexps; if it doesn’t work, try removing the two \ in the first pattern.

+1
source

All Articles