I have a file1 which has lines
abc
dfg
hij
cab
I would like to match the pattern ab in file1 and print to file2. After that delete those lines from file1. Then file1 has the following lines
dfg
hij
and file2 has lines
abc
cab
Currently, I am doing it with two lines of code
perl -ne '/ab/i && print' file1.csv > file2.csv
perl -n -i.bak -e 'print unless m/ab/' file1.csv
Can any one give me a one-liner Perl code?
Thanks,
CodePudding user response:
I'd use ed instead:
$ rm file2.csv # Just in case it already exists
$ ed -s file1.csv <<'EOF'
g/ab/.W file2.csv\
d
w
EOF
(For every line matching the basic regular expression ab, append it to file2.csv and delete the line, and then finally write the modified buffer back to file1.csv).
But one simple perl one-liner:
$ perl -ni -e 'if (/ab/) { print STDERR } else { print }' file1.csv 2>file2.csv
This prints matching lines to standard error and uses the shell to redirect that to file2.csv, while modifying file1.csv in-place with just the non-matching lines.
