Extract strings with specific patterns in separate files

The input file has the following lines and separates them using the character lines of the 2nd field "+" in one file and the character lines "-" in another file:

24 + I am the Five man 22 - Who are you? The new number two! 51 + . . . And four on the floor 42 + 16 - Who is number one? 33 - I three you. 

is it possible when $ 2 is '+', a = $ 1 + 500 and b = $ 1-500 at the same time when $ 2 is '-', a = $ 1-500 and b = $ 1 + 500? 'a' and 'b' are new variables.

+4
source share
7 answers

This will put the β€œ+” lines in file1, and the rest in file2:

 awk '{print > ("file" ($2~/+/?1:2))}' file 
+4
source

Another variant

 awk 'BEGIN{m["+"]="plus.txt";m["-"]="minus.txt"} $2 ~ /^[+-]$/{print>>m[$2]}' 
+5
source

With Perl:

 perl -lne '/^\d+ -/ && print(STDERR) || print' input 2> minus > plus 

in a slightly different form:

 perl -lpe 'select(/^\d+ -/?STDERR:STDOUT)' input 2> minus > plus 

It is also possible to use tee :

 tee >(sed -n '/^[0-9]* -/p' > minus) < input | \ sed -n '/^[0-9]* +/p' > plus 
+5
source

This solution filters the output to files f1 and f2.

 awk '{ if ($2 == "+") print >>"f1"; else if ($2=="-") print >>"f2"; }' datafile 
+4
source

Code for GNU :

 sed '/\S\+\s\++/!D' file > plus.txt sed '/\S\+\s\++/D' file > minus.txt 
+2
source

With awk you simply do:

 awk '$2=="+"{print>"f1";next}{print>"f2"}' file 

Demo:

 $ cat file 24 + I am the Five man 22 - Who are you? The new number two! 51 + . . . And four on the floor 42 + 16 - Who is number one? 33 - I three you. $ awk '$2=="+"{print>"f1";next}{print>"f2"}' file $ cat f1 24 + I am the Five man 51 + . . . And four on the floor 42 + $ cat f2 22 - Who are you? The new number two! 16 - Who is number one? 33 - I three you. 
+2
source

The title of the question is a little fuzzy, I will edit it in an instant. Meanwhile, here is the answer:

 awk '/^[0-9]+ \+/{print > "a"} /^[0-9]+ -/{print > "b"}' 
-1
source

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


All Articles