1

I am trying to make a new file from an existing file, input.txt, using Unix commands.

File input.txt

type ABC=home,3,test,data
type EFG=data,2,test_new,data_load

type PQR=load,2,test_type,data_loader

Expected output.txt

Name,number
ABC,3
EFG,2
PQR,2

I am trying with

input.txt | awk -F" "'Print $2' | awk -F","'Print $2' > output.txt

But I am not getting the expected result. How can I fix it?

0

3 Answers 3

4

You can do:

$ awk -F'[ =,]' 'BEGIN{ OFS=","; print "Name","number"; }/./{print $2,$4}' input.txt 
Name,number
ABC,3
EFG,2
PQR,2
0
1

Since you used the sed tag:

{
    echo Name,number
    sed -e '/./!d' \
        -e 'h; s/[^,]*,//; s/,.*//' \
        -e 'x; s/^type //; s/=.*//' \
        -e 'G; y/\n/,/' input.txt
} >output.txt

This first uses echo to output the header. The sed command then deletes all empty lines and extracts the wanted data from each remaining line. The output is written to output.txt.

To extract the wanted data, the sed script first saves a copy of the original input line in the hold space using h. It then deletes everything up to the first comma and after the next comma to get at the number. It then swaps in the saved line from the hold space with x and does a similar operation to get the label before the = character. The two results are then combined with G and the newline character that sed inserts is changed into a comma with the y/// command.

1

Replace space/=/, with newline, guaranteed to not be present in the pattern space. Revert the third marker and then chop the pattern space so that the 2nd and fourth fields come to the fore. Which then get printed via P

sed -ne '
  1{x;s/^/Name,Number/p;x;}
  /[^[:space:]]/!d
  y/ =,/\n\n\n/;s/\n/,/3
  s/.*\n\(.*\)\n.*,/\1,/;P
' input.txt

output:

Name,Number
ABC,3
EFG,2
PQR,2

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.