2

The following grep command that returns the files that contain the string ptrn. The sed command skips files using a step stored in stp.

grep -rl "${isufx[@]}" -e "$ptrn" -- "${fdir[@]}" |
  sed "${sta}~${stp}!d" >> $logfl

This would be the result

cat /home/flora/logs/27043-T13:09:44.893003954.log
file1.sh
file2.sh
file3.sh
file4.sh
file5.sh
file6.sh

I would like to end up with the following

cat /home/flora/logs/27043-T13:09:44.893003954.log
File: file1.sh
+ file2.sh
+ file3.sh
+ file4.sh
+ file5.sh
+ file6.sh

I do not think one can do that with grep though. Some will likely recommend using awk on the file logfl.

5
  • So all you want is add prefix File: in 1st line and + in all other lines? Commented Nov 21, 2021 at 19:42
  • What are the values of your variables? Commented Nov 21, 2021 at 19:44
  • Yes, that is shat I want to do @alecxs. Have put one solution. Would you have a better one, if I may ask? Commented Nov 21, 2021 at 20:33
  • Oh you already found yourself what I had in mind :) Commented Nov 21, 2021 at 20:36
  • Fantastic. Respect buddy. I got a further challenge. Interested @alecxs? Commented Nov 21, 2021 at 20:48

2 Answers 2

3

Using GNU rectools (which you mention in comments to another of your questions):

: >output

recins -f File -v "$(cat logfile)" output

This creates or empties the file called output, and then inserts a single field called File with a value that is the contents of the file logfile.

Note that the + counts as a newline character in the GNU recfile format, so what the above does is to insert a single value, containing embedded newline characters.

If you want to insert each filename as a separate element, you could use

: >output

xargs -I {} recins -f File -v {} output <logfile

The above calls recins once per line in logfile and inserts a separate key-value pair for each.

This could be done more efficiently if we let the input be a CSV file:

{ echo File; cat logfile; } | csv2rec >output

The echo command is used here to prepend the CSV header to the input data for csv2rec.

2

I solved the problem this way

 grep -rl "${isufx[@]}" -e "$ptrn" -- "${fdir[@]}" |
    sed '1s/^/File: /;1!s/^/+ /' >> $logfl

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.