Move rows to file by number of columns using awk

I have a sample file with '|| o || ' as a field separator.

www.google.org||o||srScSG2C5tg=||o||bngwq farhansingla.it||o||4sQVj09gpls=||o|| ngascash||o||||o|| ms-bronze.com.br||o||||o|| 

I want to move lines with only one field in 1.txt and with more than 1 field in not_1.txt . I use the following command:

 sed 's/\(||o||\)\+$//g' sample.txt | awk -F '[|][|]o[|][|]' '{if (NF == 1) print > "1.txt"; else print > "not_1.txt" }' 

The problem is that it does not move the original rows, but replaced ones.

The output I get is (not_1.txt):

 td@the-end.org ||o||srScSG2C5tg=||o||bnm erba01@tiscali.it ||o||4sQVj09gpls= 

1.txt:

 ngas ms-inside@bol.com.br 

As you can see, the source lines are changed. I do not want to change the lines. Any help would be greatly appreciated.

+5
source share
2 answers

Awk :

 awk -F '[|][|]o[|][|]' \ '{ c = 0; for (i=1; i<=NF; i++) if ($i != "") c++; print > (c == 1? "1" : "not_1")".txt" }' sample.txt 

Results:

 $ head 1.txt not_1.txt ==> 1.txt <== ngascash||o||||o|| ms-bronze.com.br||o||||o|| ==> not_1.txt <== www.google.org||o||srScSG2C5tg=||o||bngwq farhansingla.it||o||4sQVj09gpls=||o|| 
+3
source

The following awk can help you with this.

 awk -F'\\|\\|o\\|\\|' '{for(i=1;i<=NF;i++){count=$i?++count:count};if(count==1){print > "1_field_only"};if(count>1){print > "not_1_field"};count=""}' Input_file 

Now add another Liner form.

 awk -F'\\|\\|o\\|\\|' ' { for(i=1;i<=NF;i++){ count=$i?++count:count }; if(count==1) { print > "1_field_only" }; if(count>1) { print > "not_1_field" }; count="" } ' Input_file 

Explanation: Now adding an explanation for the above code.

 awk -F'\\|\\|o\\|\\|' ' ##Setting field separator as ||o|| here and escaping the | here to take it literal character here. { for(i=1;i<=NF;i++){ count=$i?++count:count }; ##Starting a for loop to traverse through all the fields here, increasing variable count value if a field is NOT null. if(count==1) { print > "1_field_only" }; ##Checking if count value is 1 it means fields are only 1 in line so printing current line into 1_field_only file. if(count>1) { print > "not_1_field" }; ##Checking if count is more than 1 so printing current line into output file named not_1_field file here. count="" ##Nullifying the variable count here. } ' Input_file ##Mentioning Input_file name here. 
+3
source

Source: https://habr.com/ru/post/1276082/


All Articles