简体   繁体   中英

bash move groups of lines to a new file

In a bash script I have phpcpd checking the entire code base and outputting to a file. I am then wanting to create new files detailing where specific files have duplicate code.

The output of phpcpd contains groups of n lines together, separating these groups of lines is an empty line.

I am attempting to add to my bash script to copy all groups of lines that match a pattern ($FILENAME) and put the remaining data in a new file.

I am uncertain of how to do this and do not have a code sample.

edited for example;

file to search for pattern contains something similar to the following;

/home/dir/fileName1
/home/dir/fileName2
/home/dir/fileName3

/home/dir/fileName4
/home/dir/fileName5

/home/dir/fileName1
/home/dir/fileName6

then lets say i want to search for fileName1, a new file named fileName1Results should contain the following;

/home/dir/fileName1
/home/dir/fileName2
/home/dir/fileName3

/home/dir/fileName1
/home/dir/fileName6

Edited based on example: Quick perl to do what you want, sets the line separator to a blank line, reads FILENAME variable and writes to ${FILENAME}Results file.

$ cat infile
/home/dir/fileName1
/home/dir/fileName2
/home/dir/fileName3

/home/dir/fileName4
/home/dir/fileName5

/home/dir/fileName1
/home/dir/fileName6
$ FILENAME=fileName1
$ perl -se '$/ = "\n\n"; while (<>) { print $_ if /\Q$f\E/; }' -- -f="$FILENAME" > "${FILENAME}Results" <infile
$ cat "${FILENAME}Results"
/home/dir/fileName1
/home/dir/fileName2
/home/dir/fileName3

/home/dir/fileName1
/home/dir/fileName6

Edit: tweaked to handle special characters (in case you have them in your filenames).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM