Search code examples
awkoutputlinefilenames

awk to manipulate multiple files


I have the following files file1 and file2 (as example)

$cat file1.txt
SERVICE: 1
TASK: 1
RESULT: 1
ADDITIONAL: 1

SERVICE: 2
TASK: 2
RESULT: 2
ADDITIONAL: 2

SERVICE: 3
TASK: 3
RESULT: 3
ADDITIONAL: 3

$cat file2.txt
SERVICE: 1
TASK: 1
RESULT: 1
ADDITIONAL: 1

SERVICE: 2
TASK: 2
RESULT: 2
ADDITIONAL: 2

SERVICE: 3
TASK: 3
RESULT: 3
ADDITIONAL: 3

I need the following output:

name of the file and each block looping on SERVICE: in 1 line like below separate by pipe "|"

file1.txt | SERVICE: 1 | TASK: 1 | RESULT: 1 | ADDITIONAL: 1
file1.txt | SERVICE: 2 | TASK: 2 | RESULT: 2 | ADDITIONAL: 2
file1.txt | SERVICE: 3 | TASK: 3 | RESULT: 3 | ADDITIONAL: 3

file2.txt | SERVICE: 1 | TASK: 1 | RESULT: 1 | ADDITIONAL: 1
file2.txt | SERVICE: 2 | TASK: 2 | RESULT: 2 | ADDITIONAL: 2
file2.txt | SERVICE: 3 | TASK: 3 | RESULT: 3 | ADDITIONAL: 3

can you help me find a way to achieve this

so far i am able to put it in line but i have issue to get the file name in front of each block looping on SERVICE:

the command i have is the following :

cat * | awk -F ":" '/^SERVICE:/ {print ""} {printf"|" substr($0, index($0,$1))}'

many thanks for your help


Solution

  • $ awk -v RS= -F'\n' -v OFS=' | ' '{$1 = FILENAME OFS $1}1' file1.txt file2.txt
    file1.txt | SERVICE: 1 | TASK: 1 | RESULT: 1 | ADDITIONAL: 1
    file1.txt | SERVICE: 2 | TASK: 2 | RESULT: 2 | ADDITIONAL: 2
    file1.txt | SERVICE: 3 | TASK: 3 | RESULT: 3 | ADDITIONAL: 3
    file2.txt | SERVICE: 1 | TASK: 1 | RESULT: 1 | ADDITIONAL: 1
    file2.txt | SERVICE: 2 | TASK: 2 | RESULT: 2 | ADDITIONAL: 2
    file2.txt | SERVICE: 3 | TASK: 3 | RESULT: 3 | ADDITIONAL: 3