AWK if 3rd line starts with " merge it with second line

163 Views Asked by At

I have some corrupted .txt files, in which I need to fix first 3 lines.

How it should be:

Template=1.0
SKU, Standard Price, Minimum Age Recommendation
sku, standard_prive, mg_recommendation

After it got corrupted:

Template=1.0
SKU, Standard Price, "Minimum Age Recommendation
"
sku, standard_prive, mg_recommendation

in some cases:

Template=1.0
SKU, Standard Price, "Minimum Age
" Recommendation
sku, standard_prive, mg_recommendation

I need to check if first line starts with quote mark, if yes, then merge 3rd line with second line.

otherwise I can't import the file as it fails to find proper headings in 3rd line.

AWK is preferred, because I already performing other task with it. I can't figure out, how I could check 3rd line value while I'm on 2nd value in the awk loop.

4

There are 4 best solutions below

0
On BEST ANSWER
$ awk '{printf "%s%s", (NR==1||/^\"/?"":ORS),$0}' file
How it should be:

Template=1.0
SKU, Standard Price, Minimum Age Recommendation
sku, standard_prive, mg_recommendation

After it got corrupted:

Template=1.0
SKU, Standard Price, "Minimum Age Recommendation"
sku, standard_prive, mg_recommendation

in some cases:

Template=1.0
SKU, Standard Price, "Minimum Age" Recommendation
sku, standard_prive, mg_recommendation

Solution preceeds records that don't start with " with a newline. Downside is that the last record ends without a newline. END{print ""} fixes that.

0
On

You can use awk like this:

awk -F, 'FNR==2 {sub(/"/,"")} FNR==3 && $0 ="\"" {next} 1' yourfile > convertedfile
  • on line 2 it replace quote with nothing
  • for line3 if it is a single qoute it skips this line
4
On

Aidas, could you please try following and let me know if this helps you.

awk '{if($0 ~ /^\"/){printf("%s",Q);Q="";};print;Q=$0}'  Input_file

EDIT: Adding one more solution where it skips those lines in Input_file which are starting from string("). It wouldn't look for line number each line which starts from " it skips.

awk '/^\"$/{next} 1' Input_file
0
On
awk '{sub(/\"/,"")}NF' file 

Template=1.0
SKU, Standard Price, Minimum Age Recommendation
sku, standard_prive, mg_recommendation