asterbraid commited on
Commit
b85888c
·
verified ·
1 Parent(s): cadabc1

Reviewed real Stack Overflow awk tasks with execution verification and attribution

Browse files
ATTRIBUTION.md ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Source attribution
2
+
3
+ - [Using awk to remove the Byte-order mark](https://stackoverflow.com/questions/1068650/using-awk-to-remove-the-byte-order-mark) — question: Boldewyn; accepted answer: Bartosz (answer 1068700).
4
+
5
+ - [How to check if the variable value in AWK script is null or empty?](https://stackoverflow.com/questions/11952854/how-to-check-if-the-variable-value-in-awk-script-is-null-or-empty) — question: samarth; accepted answer: Levon (answer 11952924).
6
+
7
+ - [Swap two columns - awk, sed, python, perl](https://stackoverflow.com/questions/11967776/swap-two-columns-awk-sed-python-perl) — question: Charley Farley; accepted answer: perreal (answer 11967849).
8
+
9
+ - [Using multiple delimiters in awk](https://stackoverflow.com/questions/12204192/using-multiple-delimiters-in-awk) — question: Satish; accepted answer: embedded.kyle (answer 12204350).
10
+
11
+ - [Remove all text before colon](https://stackoverflow.com/questions/12297859/remove-all-text-before-colon) — question: NewUsr_stat; accepted answer: Sacha Epskamp (answer 12297934).
12
+
13
+ - [Printing the last column of a line in a file](https://stackoverflow.com/questions/13046167/printing-the-last-column-of-a-line-in-a-file) — question: Rayne; accepted answer: Olaf Dietsche (answer 13046224).
14
+
15
+ - [How to delete duplicate lines in a file without sorting it in Unix](https://stackoverflow.com/questions/1444406/how-to-delete-duplicate-lines-in-a-file-without-sorting-it-in-unix) — question: Vijay; accepted answer: Jonas Elfström (answer 1444448).
16
+
17
+ - [How to get first n characters of each line in unix data file](https://stackoverflow.com/questions/14462529/how-to-get-first-n-characters-of-each-line-in-unix-data-file) — question: Teja; accepted answer: Chris Seymour (answer 14462614).
18
+
19
+ - [using awk with column value conditions](https://stackoverflow.com/questions/14739057/using-awk-with-column-value-conditions) — question: user1687130; accepted answer: Rob Davis (answer 14739101).
20
+
21
+ - [Select row and element in awk](https://stackoverflow.com/questions/1506521/select-row-and-element-in-awk) — question: Tim; accepted answer: Dennis Williamson (answer 1506601).
22
+
23
+ - [Scripts for computing the average of a list of numbers in a data file](https://stackoverflow.com/questions/15681498/scripts-for-computing-the-average-of-a-list-of-numbers-in-a-data-file) — question: JackWM; accepted answer: Chris Seymour (answer 15681543).
24
+
25
+ - [How can I get the second column from command output?](https://stackoverflow.com/questions/16136943/how-can-i-get-the-second-column-from-command-output) — question: Qiang Xu; accepted answer: catay (answer 16137100).
26
+
27
+ - [awk partly string match (if column/word partly matches)](https://stackoverflow.com/questions/17001849/awk-partly-string-match-if-column-word-partly-matches) — question: pogibas; accepted answer: Ahmed Masud (answer 17001897).
28
+
29
+ - [How to select lines between two marker patterns which may occur multiple times with awk/sed](https://stackoverflow.com/questions/17988756/how-to-select-lines-between-two-marker-patterns-which-may-occur-multiple-times-w) — question: dvai; accepted answer: fedorqui (answer 17988834).
30
+
31
+ - [Use awk to find average of a column](https://stackoverflow.com/questions/19149731/use-awk-to-find-average-of-a-column) — question: Ben Zifkin; accepted answer: imp25 (answer 19150191).
32
+
33
+ - [Trim leading and trailing spaces from a string in awk](https://stackoverflow.com/questions/20600982/trim-leading-and-trailing-spaces-from-a-string-in-awk) — question: Marjer; accepted answer: Floris (answer 20601021).
34
+
35
+ - [Print line numbers starting at zero using awk](https://stackoverflow.com/questions/20752043/print-line-numbers-starting-at-zero-using-awk) — question: user790049; accepted answer: Lance Roberts (answer 20752092).
36
+
37
+ - [Print second-to-last column/field in `awk`](https://stackoverflow.com/questions/2096490/print-second-to-last-column-field-in-awk) — question: Brian G; accepted answer: Chris Kannon (answer 2096526).
38
+
39
+ - [cut or awk command to print first field of first row](https://stackoverflow.com/questions/22190902/cut-or-awk-command-to-print-first-field-of-first-row) — question: user3331975; accepted answer: devnull (answer 22190928).
40
+
41
+ - [How to remove leading whitespace from each line in a file](https://stackoverflow.com/questions/2310605/how-to-remove-leading-whitespace-from-each-line-in-a-file) — question: Lazer; accepted answer: shuvalov (answer 2310620).
42
+
43
+ - [Print all but the first three columns](https://stackoverflow.com/questions/2626274/print-all-but-the-first-three-columns) — question: hhh; accepted answer: olibre (answer 18817331).
44
+
45
+ - [How can I quickly sum all numbers in a file?](https://stackoverflow.com/questions/2702564/how-can-i-quickly-sum-all-numbers-in-a-file) — question: Mark Roberts; accepted answer: brian d foy (answer 2702614).
46
+
47
+ - [awk - concatenate two string variable and assign to a third](https://stackoverflow.com/questions/27028928/awk-concatenate-two-string-variable-and-assign-to-a-third) — question: user3738926; accepted answer: fedorqui (answer 27028953).
48
+
49
+ - [How to Sum a column in AWK?](https://stackoverflow.com/questions/28905083/how-to-sum-a-column-in-awk) — question: Ajo; accepted answer: mpromonet (answer 28905292).
50
+
51
+ - [How to use awk to print lines where a field matches a specific string?](https://stackoverflow.com/questions/2957094/how-to-use-awk-to-print-lines-where-a-field-matches-a-specific-string) — question: yael; accepted answer: Hank Gay (answer 2957225).
52
+
53
+ - [Using awk to print all columns from the nth to the last](https://stackoverflow.com/questions/2961635/using-awk-to-print-all-columns-from-the-nth-to-the-last) — question: Andy; accepted answer: zed_0xff (answer 2961994).
54
+
55
+ - [Print the last line of a file, from the CLI](https://stackoverflow.com/questions/3080693/print-the-last-line-of-a-file-from-the-cli) — question: yael; accepted answer: Joey (answer 3080722).
56
+
57
+ - [How to print lines between two patterns, inclusive or exclusive (in sed, AWK or Perl)?](https://stackoverflow.com/questions/38972736/how-to-print-lines-between-two-patterns-inclusive-or-exclusive-in-sed-awk-or) — question: fedorqui; accepted answer: fedorqui (answer 38972737).
58
+
59
+ - [Printing everything except the first field with awk](https://stackoverflow.com/questions/4198138/printing-everything-except-the-first-field-with-awk) — question: cfischer; accepted answer: Ben Jackson (answer 4198169).
60
+
61
+ - [How to print last two columns using awk](https://stackoverflow.com/questions/4304917/how-to-print-last-two-columns-using-awk) — question: vehomzzz; accepted answer: codaddict (answer 4304949).
62
+
63
+ - [How to print all the columns after a particular number using awk?](https://stackoverflow.com/questions/5081916/how-to-print-all-the-columns-after-a-particular-number-using-awk) — question: Lazer; accepted answer: Amadan (answer 5082055).
64
+
65
+ - [Tab separated values in awk](https://stackoverflow.com/questions/5374239/tab-separated-values-in-awk) — question: shantanuo; accepted answer: glenn jackman (answer 5376527).
66
+
67
+ - [How to print matched regex pattern using awk?](https://stackoverflow.com/questions/5536018/how-to-print-matched-regex-pattern-using-awk) — question: marverix; accepted answer: kurumi (answer 5536068).
68
+
69
+ - [Bash tool to get nth line from a file](https://stackoverflow.com/questions/6022384/bash-tool-to-get-nth-line-from-a-file) — question: Vlad Vivdovitch; accepted answer: anubhava (answer 6022431).
70
+
71
+ - [How to split a delimited string into an array in awk?](https://stackoverflow.com/questions/8009664/how-to-split-a-delimited-string-into-an-array-in-awk) — question: Mohamed Saligh; accepted answer: Calin Paul Alexandru (answer 8009724).
72
+
73
+ - [How to print the number of characters in each line of a text file](https://stackoverflow.com/questions/8786634/how-to-print-the-number-of-characters-in-each-line-of-a-text-file) — question: vikas368; accepted answer: Fred Foo (answer 8786674).
74
+
75
+ - [How can I get the length of an array in awk?](https://stackoverflow.com/questions/9351902/how-can-i-get-the-length-of-an-array-in-awk) — question: softghost; accepted answer: shellter (answer 9351954).
76
+
77
+ - [How to add to the end of lines containing a pattern with sed or awk?](https://stackoverflow.com/questions/9591744/how-to-add-to-the-end-of-lines-containing-a-pattern-with-sed-or-awk) — question: yasar; accepted answer: user219882 (answer 9591835).
78
+
79
+ - [How to merge every two lines into one from the command line?](https://stackoverflow.com/questions/9605232/how-to-merge-every-two-lines-into-one-from-the-command-line) — question: shantanuo; accepted answer: Kent (answer 9605559).
LICENSE ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
README.md ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: cc-by-sa-4.0
3
+ language: en
4
+ pretty_name: Awkweave Real Questions
5
+ size_categories:
6
+ - n<1K
7
+ task_categories:
8
+ - text-generation
9
+ tags:
10
+ - awk
11
+ - code-generation
12
+ - text-to-code
13
+ - execution-verified
14
+ - stackoverflow
15
+ configs:
16
+ - config_name: default
17
+ data_files:
18
+ - split: train
19
+ path: data/train.jsonl
20
+ ---
21
+
22
+ # Awkweave Real Questions
23
+
24
+ A small set of natural-language-to-`awk` tasks derived from highly voted Stack Overflow questions and accepted answers, used to reduce synthetic-phrasing bias in Awkweave.
25
+
26
+ ## Contents
27
+
28
+ - 39 reviewed original tasks with unique source questions.
29
+ - 33 accepted paraphrases and 6 guarded original-wording copies.
30
+ - 78 rows total, all with two different input texts and actual outputs from both.
31
+
32
+ Every program was executed on both inputs with `mawk 1.3.4 20200120`: **156 successful executions, 0 errors**. One unsuitable process-killing conversion was manually excluded. Programs are bare `awk`, read a single stream on stdin, and avoid files, pipelines, subprocesses, and output redirection.
33
+
34
+ ## Source and attribution
35
+
36
+ Each row includes `question_url`, `question_title`, `question_owner`, `answer_owner`, and `answer_id`. These fields identify the original authors and sources. `ATTRIBUTION.md` lists all source questions. `request` is a self-contained instruction derived from the question and accepted answer; `program` is an executable solution.
37
+
38
+ ```python
39
+ from datasets import load_dataset
40
+
41
+ ds = load_dataset("asterbraid/awkweave-so-data", split="train")
42
+ print(ds[0])
43
+ ```
44
+
45
+ ## Limitations
46
+
47
+ This is a small, high-vote sample, not a representative sample of all `awk` use. Execution verifies that reference programs run and produce the stored outputs; request-to-program intent was also reviewed. The data is not a new benchmark and was not included in the Awkweave frozen evaluation.
48
+
49
+ ## License
50
+
51
+ Original Stack Overflow content and these derived rows are **CC BY-SA 4.0**. See `SO_DATASET_LICENSE.txt` and `ATTRIBUTION.md`. Included conversion code is Apache-2.0.
SO_DATASET_LICENSE.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ Awkweave Stack Overflow-derived rows are licensed under Creative Commons Attribution-ShareAlike 4.0 International (CC BY-SA 4.0).
2
+
3
+ The rows are derived from Stack Overflow questions and accepted answers. Each row includes the question URL, question title, question author, answer author, and answer ID. The original questions and answers remain the work of their respective authors. Listings and generated attribution files in this repository are provided by Asterbraid.
4
+
5
+ You must give appropriate credit, link to the license, indicate changes, and distribute adaptations under the same license.
6
+
7
+ License: https://creativecommons.org/licenses/by-sa/4.0/
8
+ Legal code: https://creativecommons.org/licenses/by-sa/4.0/legalcode
9
+ Stack Exchange content policy: https://stackoverflow.com/legal/terms-of-service/public
awkweave/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ """Awkweave: execution-verified natural-language-to-awk tools."""
2
+
3
+ __version__ = "0.1.0"
awkweave/execution.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ import resource
5
+ import shutil
6
+ import subprocess
7
+
8
+ MAX_INPUT_BYTES = 1_000_000
9
+ MAX_PROGRAM_CHARS = 8_000
10
+ FORBIDDEN_PATTERN = re.compile(
11
+ r"\b(?:system|getline|ARGV|ARGC|ENVIRON|FILENAME|FNR|nextfile|close)\b",
12
+ re.IGNORECASE,
13
+ )
14
+ OUTPUT_REDIRECT_PATTERN = re.compile(
15
+ r"\bprintf?\b[^;\n}]*(?:>\s*(?:[\"/]|[A-Za-z_$])|(?<!\|)\|(?!\|))",
16
+ re.IGNORECASE,
17
+ )
18
+
19
+
20
+ class UnsafeProgramError(ValueError):
21
+ pass
22
+
23
+
24
+ def check_program(program: str) -> str:
25
+ program = program.strip()
26
+ if not program:
27
+ raise UnsafeProgramError("The awk program is empty.")
28
+ if len(program) > MAX_PROGRAM_CHARS:
29
+ raise UnsafeProgramError("The awk program is too long.")
30
+ if "\x00" in program:
31
+ raise UnsafeProgramError("The awk program contains a null byte.")
32
+ match = FORBIDDEN_PATTERN.search(program)
33
+ if match:
34
+ raise UnsafeProgramError(f"File, environment, and process access are not allowed: {match.group()}")
35
+ if OUTPUT_REDIRECT_PATTERN.search(program):
36
+ raise UnsafeProgramError("Output redirection and pipes are not allowed.")
37
+ return program
38
+
39
+
40
+ def limit_resources() -> None:
41
+ resource.setrlimit(resource.RLIMIT_CPU, (2, 2))
42
+ resource.setrlimit(resource.RLIMIT_AS, (256_000_000, 256_000_000))
43
+ resource.setrlimit(resource.RLIMIT_FSIZE, (1_000_000, 1_000_000))
44
+ resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
45
+ resource.setrlimit(resource.RLIMIT_NOFILE, (16, 16))
46
+
47
+
48
+ def run_awk(program: str, input_text: str, timeout: float = 3.0) -> str:
49
+ program = check_program(program)
50
+ if len(input_text.encode("utf-8")) > MAX_INPUT_BYTES:
51
+ raise ValueError("Input text exceeds the 1 MB limit.")
52
+ executable = shutil.which("awk")
53
+ if executable is None:
54
+ raise RuntimeError("No awk executable is available on PATH.")
55
+ result = subprocess.run(
56
+ [executable, program],
57
+ input=input_text,
58
+ text=True,
59
+ capture_output=True,
60
+ timeout=timeout,
61
+ env={"LC_ALL": "C", "PATH": "/usr/bin:/bin"},
62
+ preexec_fn=limit_resources,
63
+ start_new_session=True,
64
+ check=False,
65
+ )
66
+ if result.returncode != 0:
67
+ raise ValueError(result.stderr.strip() or f"awk exited with status {result.returncode}")
68
+ return result.stdout
awkweave/prompts.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ SYSTEM_PROMPT = """You write POSIX awk programs for text-processing requests. Given a request and sample input, return only the awk program, not the awk command or Markdown. Do not read or write files, invoke commands, or explain."""
2
+
3
+
4
+ def user_prompt(request: str, input_text: str) -> str:
5
+ return f"Request:\n{request.strip()}\n\nSample input:\n```text\n{input_text.rstrip()}\n```"
6
+
7
+
8
+ def messages(request: str, input_text: str) -> list[dict[str, str]]:
9
+ return [
10
+ {"role": "system", "content": SYSTEM_PROMPT},
11
+ {"role": "user", "content": user_prompt(request, input_text)},
12
+ ]
convert_real_questions.py ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import concurrent.futures
4
+ import html
5
+ import html.parser
6
+ import json
7
+ import os
8
+ import time
9
+ import urllib.request
10
+ from pathlib import Path
11
+
12
+ from awkweave.execution import run_awk
13
+
14
+ MODEL = "qwen/qwen3.7-plus"
15
+
16
+
17
+ class TextExtractor(html.parser.HTMLParser):
18
+ def __init__(self):
19
+ super().__init__()
20
+ self.parts = []
21
+ self.skip = 0
22
+
23
+ def handle_starttag(self, tag, attrs):
24
+ if tag in {"script", "style"}:
25
+ self.skip += 1
26
+ if tag in {"p", "br", "pre", "code", "li", "tr"}:
27
+ self.parts.append("\n")
28
+
29
+ def handle_endtag(self, tag):
30
+ if tag in {"script", "style"} and self.skip:
31
+ self.skip -= 1
32
+ if tag in {"p", "pre", "code", "li", "tr"}:
33
+ self.parts.append("\n")
34
+
35
+ def handle_data(self, data):
36
+ if not self.skip:
37
+ self.parts.append(data)
38
+
39
+
40
+ def plain(value: str) -> str:
41
+ parser = TextExtractor()
42
+ parser.feed(value)
43
+ text = html.unescape("".join(parser.parts))
44
+ return "\n".join(line.strip() for line in text.splitlines() if line.strip())
45
+
46
+
47
+ def convert_batch(items: list[dict]) -> list[dict]:
48
+ context = []
49
+ for item in items:
50
+ question = item["question"]
51
+ answer = item["answer"]
52
+ context.append({
53
+ "question_id": question["question_id"],
54
+ "title": question["title"],
55
+ "question": plain(question["body"])[:5000],
56
+ "accepted_answer": plain(answer["body"])[:5000],
57
+ })
58
+ payload = {
59
+ "model": MODEL,
60
+ "messages": [
61
+ {
62
+ "role": "system",
63
+ "content": (
64
+ "Convert real Stack Overflow awk questions into executable training tasks. Return only valid JSON "
65
+ "with a tasks array. Include only questions solvable by one POSIX awk program reading a single text "
66
+ "stream on stdin. Skip sed-only, multi-file, pipeline, file access, shell variable, interactive, "
67
+ "network, and general discussion questions. For each suitable question return question_id, request, "
68
+ "program, input_text, and validation_input. The request must be a natural, self-contained English "
69
+ "instruction preserving the question's intent. The program must be bare awk without the awk executable "
70
+ "or filename and must not use system, getline, ARGV, ENVIRON, pipes, or output redirection. Provide "
71
+ "two different representative inputs with up to 8 lines each and the same schema. Do not hardcode "
72
+ "answers into the program. Do not include expected outputs; they will be computed by execution."
73
+ ),
74
+ },
75
+ {"role": "user", "content": "Return {\"tasks\": [...]} or an empty list when unsuitable.\n" + json.dumps(context, ensure_ascii=False)},
76
+ ],
77
+ "response_format": {"type": "json_object"},
78
+ "temperature": 0.2,
79
+ "max_tokens": 6000,
80
+ "reasoning": {"enabled": False},
81
+ }
82
+ request = urllib.request.Request(
83
+ os.environ["OPENROUTER_BASE_URL"].rstrip("/") + "/chat/completions",
84
+ data=json.dumps(payload).encode("utf-8"),
85
+ headers={"Authorization": "Bearer " + os.environ["OPENROUTER_API_KEY"], "Content-Type": "application/json"},
86
+ )
87
+ for attempt in range(5):
88
+ try:
89
+ with urllib.request.urlopen(request, timeout=180) as response:
90
+ data = json.load(response)
91
+ return json.loads(data["choices"][0]["message"]["content"])["tasks"]
92
+ except Exception:
93
+ if attempt == 4:
94
+ raise
95
+ time.sleep(min(30, 2 ** attempt))
96
+ raise AssertionError("unreachable")
97
+
98
+
99
+ def main() -> None:
100
+ questions = json.load(open(".tmp/awk-questions.json"))["items"]
101
+ answers = json.load(open(".tmp/awk-answers.json"))
102
+ items = []
103
+ for question in questions:
104
+ if "accepted_answer_id" in question:
105
+ items.append({"question": question, "answer": answers[str(question["accepted_answer_id"])]})
106
+ batches = [items[index:index + 4] for index in range(0, len(items), 4)]
107
+ raw = []
108
+ with concurrent.futures.ThreadPoolExecutor(max_workers=4) as executor:
109
+ futures = {executor.submit(convert_batch, batch): batch for batch in batches}
110
+ for future in concurrent.futures.as_completed(futures):
111
+ try:
112
+ raw.extend(future.result())
113
+ except Exception as error:
114
+ print("batch failed", error, flush=True)
115
+ Path(".tmp/awk-converted-raw.json").write_text(json.dumps(raw, indent=2), encoding="utf-8")
116
+
117
+ accepted = []
118
+ skipped = []
119
+ seen = set()
120
+ for item in raw:
121
+ question_id = item.get("question_id")
122
+ if question_id in seen:
123
+ continue
124
+ seen.add(question_id)
125
+ matching = next((entry for entry in items if entry["question"]["question_id"] == question_id), None)
126
+ if matching is None:
127
+ continue
128
+ try:
129
+ request_text = item["request"].strip()
130
+ program = item["program"].strip()
131
+ input_text = item["input_text"]
132
+ validation_input = item["validation_input"]
133
+ if not request_text or input_text == validation_input:
134
+ raise ValueError("Missing request or identical inputs")
135
+ expected = run_awk(program, input_text)
136
+ validation_expected = run_awk(program, validation_input)
137
+ if not expected.strip() or not validation_expected.strip():
138
+ raise ValueError("Empty output")
139
+ question = matching["question"]
140
+ answer = matching["answer"]
141
+ accepted.append({
142
+ "id": f"so-{question_id}", "request": request_text, "program": program,
143
+ "input_text": input_text, "expected_output": expected,
144
+ "validation_input": validation_input, "validation_output": validation_expected,
145
+ "family": "real-stackoverflow", "difficulty": 3, "split": "train",
146
+ "source": "stackoverflow-accepted-answer", "license": "CC-BY-SA-4.0",
147
+ "question_url": question["link"], "question_title": question["title"],
148
+ "question_owner": question["owner"].get("display_name"),
149
+ "answer_owner": answer["owner"].get("display_name"),
150
+ "answer_id": answer["answer_id"], "question_score": question["score"],
151
+ })
152
+ except Exception as error:
153
+ skipped.append({"question_id": question_id, "reason": str(error)[:300]})
154
+ with open("awkweave-so.jsonl", "w", encoding="utf-8") as handle:
155
+ for row in accepted:
156
+ handle.write(json.dumps(row, ensure_ascii=False, separators=(",", ":")) + "\n")
157
+ Path(".tmp/awk-converted-skipped.json").write_text(json.dumps(skipped, indent=2), encoding="utf-8")
158
+ print(f"accepted {len(accepted)} tasks; skipped {len(skipped)} invalid tasks from {len(raw)} candidates")
159
+
160
+
161
+ if __name__ == "__main__":
162
+ main()
data/train.jsonl ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {"id":"so-1068650","request":"Write an awk program that removes the UTF-8 Byte Order Mark (BOM) from the beginning of the first line of input. The BOM consists of the bytes EF BB BF. If the first line starts with these characters, remove them. Print all lines.","program":"NR==1{sub(/^\\xef\\xbb\\xbf/,\"\")}1","input_text":"Hello World\nSecond Line\nThird Line","expected_output":"Hello World\nSecond Line\nThird Line\n","validation_input":"No BOM Here\nAnother Line","validation_output":"No BOM Here\nAnother Line\n","family":"real-stackoverflow","difficulty":3,"split":"train","source":"stackoverflow-accepted-answer","license":"CC-BY-SA-4.0","question_url":"https://stackoverflow.com/questions/1068650/using-awk-to-remove-the-byte-order-mark","question_title":"Using awk to remove the Byte-order mark","question_owner":"Boldewyn","answer_owner":"Bartosz","answer_id":1068700,"question_score":107}
2
+ {"id":"so-11952854","request":"Write an awk program that reads lines from stdin. For each line, split the fields by whitespace. For each field, if it contains an '@' character, split it into a key and a value using '@' as the delimiter. If the resulting value part is empty or consists only of spaces, replace the value with 'Y'. Print the modified key-value pairs in the format 'key=value', one per line, preserving the order of appearance in the input.","program":"{\n for (i = 1; i <= NF; i++) {\n if (index($i, \"@\") > 0) {\n n = split($i, parts, \"@\")\n key = parts[1]\n val = \"\"\n for (j = 2; j <= n; j++) {\n if (j > 2) val = val \"@\"\n val = val parts[j]\n }\n if (val ~ /^[[:space:]]*$/) {\n val = \"Y\"\n }\n print key \"=\" val\n }\n }\n}","input_text":"user@john admin@\nhost@server1 config@ \ndata@value","expected_output":"user=john\nadmin=Y\nhost=server1\nconfig=Y\ndata=value\n","validation_input":"a@ b@ \nc@d e@f","validation_output":"a=Y\nb=Y\nc=d\ne=f\n","family":"real-stackoverflow","difficulty":3,"split":"train","source":"stackoverflow-accepted-answer","license":"CC-BY-SA-4.0","question_url":"https://stackoverflow.com/questions/11952854/how-to-check-if-the-variable-value-in-awk-script-is-null-or-empty","question_title":"How to check if the variable value in AWK script is null or empty?","question_owner":"samarth","answer_owner":"Levon","answer_id":11952924,"question_score":64}
3
+ {"id":"so-11967776","request":"Swap the first and second fields of each line in the input, preserving the rest of the line exactly as it is. Assume fields are separated by whitespace.","program":"{ temp = $1; $1 = $2; $2 = temp; print }","input_text":"Affy-id chr 0 pos NA06984\nCol1 Col2 Rest of line","expected_output":"chr Affy-id 0 pos NA06984\nCol2 Col1 Rest of line\n","validation_input":"A B C D E\nFirst Second Third","validation_output":"B A C D E\nSecond First Third\n","family":"real-stackoverflow","difficulty":3,"split":"train","source":"stackoverflow-accepted-answer","license":"CC-BY-SA-4.0","question_url":"https://stackoverflow.com/questions/11967776/swap-two-columns-awk-sed-python-perl","question_title":"Swap two columns - awk, sed, python, perl","question_owner":"Charley Farley","answer_owner":"perreal","answer_id":11967849,"question_score":83}
4
+ {"id":"so-12204192","request":"Extract the third path component, the fifth path component, and the value after the equals sign from each line. Use forward slashes and equals signs as delimiters.","program":"BEGIN { FS = \"[/=]\" } { print $3, $5, $8 }","input_text":"/logs/tc0001/tomcat/tomcat7.1/conf/catalina.properties:app.env.server.name = demo.example.com\n/logs/tc0001/tomcat/tomcat7.2/conf/catalina.properties:app.env.server.name = quest.example.com","expected_output":"tc0001 tomcat7.1 demo.example.com\ntc0001 tomcat7.2 quest.example.com\n","validation_input":"/data/projA/src/main/java/App.java:version = 1.0.0\n/data/projB/lib/utils/helper.py:mode = production","validation_output":"projA main 1.0.0\nprojB utils \n","family":"real-stackoverflow","difficulty":3,"split":"train","source":"stackoverflow-accepted-answer","license":"CC-BY-SA-4.0","question_url":"https://stackoverflow.com/questions/12204192/using-multiple-delimiters-in-awk","question_title":"Using multiple delimiters in awk","question_owner":"Satish","answer_owner":"embedded.kyle","answer_id":12204350,"question_score":306}
5
+ {"id":"so-12297859","request":"Write an awk program that reads lines from stdin. For each line, extract and print only the text that appears after the last colon character. If a line does not contain a colon, print the entire line unchanged.","program":"{idx=match($0, /:[^:]*$/); if(idx>0) print substr($0, idx+1); else print $0}","input_text":"TF_list_to_test10004/Nus_k0.345_t0.1_e0.1.adj:PKMYT1\npath/to/file:GENE_A\nno_colon_here","expected_output":"PKMYT1\nGENE_A\nno_colon_here\n","validation_input":"server:port:service_name\nsimple_line\nkey:value","validation_output":"service_name\nsimple_line\nvalue\n","family":"real-stackoverflow","difficulty":3,"split":"train","source":"stackoverflow-accepted-answer","license":"CC-BY-SA-4.0","question_url":"https://stackoverflow.com/questions/12297859/remove-all-text-before-colon","question_title":"Remove all text before colon","question_owner":"NewUsr_stat","answer_owner":"Sacha Epskamp","answer_id":12297934,"question_score":77}
6
+ {"id":"so-13046167","request":"Print the last field of every line that contains the string 'A1'.","program":"/A1/ {print $NF}","input_text":"A1 123 456\nB1 234 567\nC1 345 678\nA1 098 766\nB1 987 6545\nC1 876 5434","expected_output":"456\n766\n","validation_input":"A1 foo bar\nX1 ignore this\nA1 baz qux\nY1 skip me","validation_output":"bar\nqux\n","family":"real-stackoverflow","difficulty":3,"split":"train","source":"stackoverflow-accepted-answer","license":"CC-BY-SA-4.0","question_url":"https://stackoverflow.com/questions/13046167/printing-the-last-column-of-a-line-in-a-file","question_title":"Printing the last column of a line in a file","question_owner":"Rayne","answer_owner":"Olaf Dietsche","answer_id":13046224,"question_score":201}
7
+ {"id":"so-1444406","request":"Remove duplicate lines from the input text while preserving the order of their first occurrence.","program":"!seen[$0]++","input_text":"apple\nbanana\napple\ncherry\nbanana\ndate","expected_output":"apple\nbanana\ncherry\ndate\n","validation_input":"line1\nline2\nline1\nline3\nline2\nline4","validation_output":"line1\nline2\nline3\nline4\n","family":"real-stackoverflow","difficulty":3,"split":"train","source":"stackoverflow-accepted-answer","license":"CC-BY-SA-4.0","question_url":"https://stackoverflow.com/questions/1444406/how-to-delete-duplicate-lines-in-a-file-without-sorting-it-in-unix","question_title":"How to delete duplicate lines in a file without sorting it in Unix","question_owner":"Vijay","answer_owner":"Jonas Elfstr&#246;m","answer_id":1444448,"question_score":214}
8
+ {"id":"so-14462529","request":"Extract the first 22 characters from each line of the input text.","program":"{ print substr($0, 1, 22) }","input_text":"000000000001199998000180000 DUMMY RAG # MFR NOT ST 1999980 ZZ- 0 0 0ZZ-\n000000000002199998000180000 DUMMY RAG # MFR NOT ST 1999980 ZZ- 0 0 0ZZ-","expected_output":"0000000000011999980001\n0000000000021999980001\n","validation_input":"ABCDEFGHIJKL1234567890EXTRA\nShort","validation_output":"ABCDEFGHIJKL1234567890\nShort\n","family":"real-stackoverflow","difficulty":3,"split":"train","source":"stackoverflow-accepted-answer","license":"CC-BY-SA-4.0","question_url":"https://stackoverflow.com/questions/14462529/how-to-get-first-n-characters-of-each-line-in-unix-data-file","question_title":"How to get first n characters of each line in unix data file","question_owner":"Teja","answer_owner":"Chris Seymour","answer_id":14462614,"question_score":82}
9
+ {"id":"so-14739057","request":"Print the third field of each line where the eighth field is exactly equal to the string \"ClNonZ\".","program":"$8 == \"ClNonZ\" { print $3 }","input_text":"2 14 0.180467091 0.800424628 0 0.0566 0.0103 ClNonZ\n5 22 0.010615711 0.959660297 0.010615711 0.0476 0.0061 ClNonZ\n9 31 0.492569002 0.350318471 0.138004246 0.0485 0.0088 ClNonZ","expected_output":"0.180467091\n0.010615711\n0.492569002\n","validation_input":"1 11 0.959660297 0 0.021231423 -0.0073 -0.0031 MhZisp\n3 19 0.98089172 0 0 -0.0158 0.0124 MhNonZ\n2 14 0.180467091 0.800424628 0 0.0566 0.0103 ClNonZ","validation_output":"0.180467091\n","family":"real-stackoverflow","difficulty":3,"split":"train","source":"stackoverflow-accepted-answer","license":"CC-BY-SA-4.0","question_url":"https://stackoverflow.com/questions/14739057/using-awk-with-column-value-conditions","question_title":"using awk with column value conditions","question_owner":"user1687130","answer_owner":"Rob Davis","answer_id":14739101,"question_score":137}
10
+ {"id":"so-1506521","request":"Print the third field of the fifth line of the input.","program":"NR==5{print $3; exit}","input_text":"Line1 F1 F2 F3 F4\nLine2 F1 F2 F3 F4\nLine3 F1 F2 F3 F4\nLine4 F1 F2 F3 F4\nLine5 F1 F2 TargetValue F4","expected_output":"F2\n","validation_input":"A B C D E\n1 2 3 4 5\na b c d e\nx y z w v\np q r s t","validation_output":"r\n","family":"real-stackoverflow","difficulty":3,"split":"train","source":"stackoverflow-accepted-answer","license":"CC-BY-SA-4.0","question_url":"https://stackoverflow.com/questions/1506521/select-row-and-element-in-awk","question_title":"Select row and element in awk","question_owner":"Tim","answer_owner":"Dennis Williamson","answer_id":1506601,"question_score":108}
11
+ {"id":"so-15681498","request":"Calculate the average of all whitespace-separated numbers found in the input text stream. Output the result in the format 'ave: <value>' with default floating point precision.","program":"{s+=$1} END{if(NR>0) print \"ave:\", s/NR}","input_text":"1.00 1.23 54.4 213.2 3.4","expected_output":"ave: 1\n","validation_input":"10 20 30","validation_output":"ave: 10\n","family":"real-stackoverflow","difficulty":3,"split":"train","source":"stackoverflow-accepted-answer","license":"CC-BY-SA-4.0","question_url":"https://stackoverflow.com/questions/15681498/scripts-for-computing-the-average-of-a-list-of-numbers-in-a-data-file","question_title":"Scripts for computing the average of a list of numbers in a data file","question_owner":"JackWM","answer_owner":"Chris Seymour","answer_id":15681543,"question_score":64}
12
+ {"id":"so-16136943","request":"Extract the second column from each line of input, where the first column is a number and the second column is a double-quoted string that may contain spaces. The output should be just the quoted string.","program":"{ match($0, /\"[^\"]*\"/); print substr($0, RSTART, RLENGTH) }","input_text":"1540 \"A B\"\n6 \"C\"\n119 \"D\"","expected_output":"\"A B\"\n\"C\"\n\"D\"\n","validation_input":"100 \"Hello World\"\n200 \"Test\"\n300 \"Foo Bar Baz\"","validation_output":"\"Hello World\"\n\"Test\"\n\"Foo Bar Baz\"\n","family":"real-stackoverflow","difficulty":3,"split":"train","source":"stackoverflow-accepted-answer","license":"CC-BY-SA-4.0","question_url":"https://stackoverflow.com/questions/16136943/how-can-i-get-the-second-column-from-command-output","question_title":"How can I get the second column from command output?","question_owner":"Qiang Xu","answer_owner":"catay","answer_id":16137100,"question_score":276}
13
+ {"id":"so-17001849","request":"Print lines where the third field contains the substring 'snow'.","program":"$3 ~ /snow/ { print }","input_text":"C1 C2 C3\n1 a snow\n2 b snowman\nsnow c sowman","expected_output":"1 a snow\n2 b snowman\n","validation_input":"id name description\n1 test snowflake\n2 demo ice\n3 alpha snow","validation_output":"1 test snowflake\n3 alpha snow\n","family":"real-stackoverflow","difficulty":3,"split":"train","source":"stackoverflow-accepted-answer","license":"CC-BY-SA-4.0","question_url":"https://stackoverflow.com/questions/17001849/awk-partly-string-match-if-column-word-partly-matches","question_title":"awk partly string match (if column/word partly matches)","question_owner":"pogibas","answer_owner":"Ahmed Masud","answer_id":17001897,"question_score":126}
14
+ {"id":"so-17988756","request":"Extract and print lines that appear strictly between lines containing 'abc' and lines containing 'mno', excluding the marker lines themselves. Handle multiple occurrences of these markers throughout the file.","program":"/abc/{flag=1;next}/mno/{flag=0}flag","input_text":"abc\ndef1\nghi1\njkl1\nmno\nabc\ndef2\nghi2","expected_output":"def1\nghi1\njkl1\ndef2\nghi2\n","validation_input":"start\nabc\nline A\nline B\nmno\nend\nabc\nline C\nmno","validation_output":"line A\nline B\nline C\n","family":"real-stackoverflow","difficulty":3,"split":"train","source":"stackoverflow-accepted-answer","license":"CC-BY-SA-4.0","question_url":"https://stackoverflow.com/questions/17988756/how-to-select-lines-between-two-marker-patterns-which-may-occur-multiple-times-w","question_title":"How to select lines between two marker patterns which may occur multiple times with awk/sed","question_owner":"dvai","answer_owner":"fedorqui","answer_id":17988834,"question_score":170}
15
+ {"id":"so-19149731","request":"Calculate and print the average of the values in the second column of the input data. Print the result in the format 'Average: <value>'.","program":"{ sum += $2 } END { if (NR > 0) print \"Average: \" sum / NR }","input_text":"Alice 10\nBob 20\nCharlie 30","expected_output":"Average: 20\n","validation_input":"Item1 5.5\nItem2 4.5\nItem3 10","validation_output":"Average: 6.66667\n","family":"real-stackoverflow","difficulty":3,"split":"train","source":"stackoverflow-accepted-answer","license":"CC-BY-SA-4.0","question_url":"https://stackoverflow.com/questions/19149731/use-awk-to-find-average-of-a-column","question_title":"Use awk to find average of a column","question_owner":"Ben Zifkin","answer_owner":"imp25","answer_id":19150191,"question_score":83}
16
+ {"id":"so-20600982","request":"Write an awk program that reads comma-separated values from stdin. For each line containing a comma, remove all leading and trailing whitespace from the second field only, then print the first field, a comma, and the trimmed second field. Lines without commas should be ignored.","program":"BEGIN{FS=\",\"; OFS=\",\"} /,/{gsub(/^[ \\t]+/,\"\",$2); gsub(/[ \\t]+$/,\"\",$2); print $1,$2}","input_text":"Name, Order\nTrim, working\ncat,cat1","expected_output":"Name,Order\nTrim,working\ncat,cat1\n","validation_input":"ID , Value\n 123 , 456 \nNoCommaHere","validation_output":"ID ,Value\n 123 ,456\n","family":"real-stackoverflow","difficulty":3,"split":"train","source":"stackoverflow-accepted-answer","license":"CC-BY-SA-4.0","question_url":"https://stackoverflow.com/questions/20600982/trim-leading-and-trailing-spaces-from-a-string-in-awk","question_title":"Trim leading and trailing spaces from a string in awk","question_owner":"Marjer","answer_owner":"Floris","answer_id":20601021,"question_score":78}
17
+ {"id":"so-20752043","request":"Print each line of input prefixed with its zero-based line number followed by a comma. The first line should be numbered 0.","program":"{ print NR-1 \",\" $0 }","input_text":"line one\nline two\nline three","expected_output":"0,line one\n1,line two\n2,line three\n","validation_input":"hello\nworld","validation_output":"0,hello\n1,world\n","family":"real-stackoverflow","difficulty":3,"split":"train","source":"stackoverflow-accepted-answer","license":"CC-BY-SA-4.0","question_url":"https://stackoverflow.com/questions/20752043/print-line-numbers-starting-at-zero-using-awk","question_title":"Print line numbers starting at zero using awk","question_owner":"user790049","answer_owner":"Lance Roberts","answer_id":20752092,"question_score":87}
18
+ {"id":"so-2096490","request":"Print the second-to-last field of each input line.","program":"{print $(NF-1)}","input_text":"one two three four\nalpha beta gamma","expected_output":"three\nbeta\n","validation_input":"a b c\nd e f g h","validation_output":"b\ng\n","family":"real-stackoverflow","difficulty":3,"split":"train","source":"stackoverflow-accepted-answer","license":"CC-BY-SA-4.0","question_url":"https://stackoverflow.com/questions/2096490/print-second-to-last-column-field-in-awk","question_title":"Print second-to-last column/field in `awk`","question_owner":"Brian G","answer_owner":"Chris Kannon","answer_id":2096526,"question_score":225}
19
+ {"id":"so-22190902","request":"Print the first field of the first line of the input.","program":"NR==1{print $1; exit}","input_text":"SUSE Linux Enterprise Server 11 (x86_64)\nVERSION = 11\nPATCHLEVEL = 2","expected_output":"SUSE\n","validation_input":"Hello World Test\nSecond Line Data\nThird Line Info","validation_output":"Hello\n","family":"real-stackoverflow","difficulty":3,"split":"train","source":"stackoverflow-accepted-answer","license":"CC-BY-SA-4.0","question_url":"https://stackoverflow.com/questions/22190902/cut-or-awk-command-to-print-first-field-of-first-row","question_title":"cut or awk command to print first field of first row","question_owner":"user3331975","answer_owner":"devnull","answer_id":22190928,"question_score":114}
20
+ {"id":"so-2310605","request":"Remove all leading whitespace (spaces and tabs) from each line of the input text.","program":"{ sub(/^[ \\t]+/, \"\"); print }","input_text":" for (i = 0; i < 100; i++)\n\tfor (i = 0; i < 100; i++)\n \t for (i = 0; i < 100; i++)","expected_output":"for (i = 0; i < 100; i++)\nfor (i = 0; i < 100; i++)\nfor (i = 0; i < 100; i++)\n","validation_input":"\t\tindented line\n mixed spaces and tabs\nno indent","validation_output":"indented line\nmixed spaces and tabs\nno indent\n","family":"real-stackoverflow","difficulty":3,"split":"train","source":"stackoverflow-accepted-answer","license":"CC-BY-SA-4.0","question_url":"https://stackoverflow.com/questions/2310605/how-to-remove-leading-whitespace-from-each-line-in-a-file","question_title":"How to remove leading whitespace from each line in a file","question_owner":"Lazer","answer_owner":"shuvalov","answer_id":2310620,"question_score":83}
21
+ {"id":"so-2626274","request":"Print all columns except the first three, preserving original spacing between the remaining fields.","program":"{ sub(/([^ ]+ +){3}/, \"\"); print }","input_text":"1 2 3 4 5 6 7\na b c d e f g h\n10 20 30 40","expected_output":"1 2 3 4 5 6 7\na b c d e f g h\n10 20 30 40\n","validation_input":"first second third fourth fifth\n1 2 3 4 5 6\nx y z w","validation_output":"first second third fourth fifth\n1 2 3 4 5 6\nx y z w\n","family":"real-stackoverflow","difficulty":3,"split":"train","source":"stackoverflow-accepted-answer","license":"CC-BY-SA-4.0","question_url":"https://stackoverflow.com/questions/2626274/print-all-but-the-first-three-columns","question_title":"Print all but the first three columns","question_owner":"hhh","answer_owner":"olibre","answer_id":18817331,"question_score":125}
22
+ {"id":"so-2702564","request":"Calculate and print the sum of all numbers provided in the input, with one number per line.","program":"{ sum += $1 } END { print sum }","input_text":"34\n42\n11\n6\n2\n99","expected_output":"194\n","validation_input":"10\n20\n30","validation_output":"60\n","family":"real-stackoverflow","difficulty":3,"split":"train","source":"stackoverflow-accepted-answer","license":"CC-BY-SA-4.0","question_url":"https://stackoverflow.com/questions/2702564/how-can-i-quickly-sum-all-numbers-in-a-file","question_title":"How can I quickly sum all numbers in a file?","question_owner":"Mark Roberts","answer_owner":"brian d foy","answer_id":2702614,"question_score":275}
23
+ {"id":"so-27028928","request":"Concatenate the first and second fields of each line with a space in between and print the result.","program":"{print $1 \" \" $2}","input_text":"hello how are you\ni am fine thanks","expected_output":"hello how\ni am\n","validation_input":"foo bar baz\nalpha beta gamma","validation_output":"foo bar\nalpha beta\n","family":"real-stackoverflow","difficulty":3,"split":"train","source":"stackoverflow-accepted-answer","license":"CC-BY-SA-4.0","question_url":"https://stackoverflow.com/questions/27028928/awk-concatenate-two-string-variable-and-assign-to-a-third","question_title":"awk - concatenate two string variable and assign to a third","question_owner":"user3738926","answer_owner":"fedorqui","answer_id":27028953,"question_score":108}
24
+ {"id":"so-28905083","request":"Calculate and print the sum of the 57th comma-separated field across all lines in the input.","program":"BEGIN { FS=\",\"; sum=0 } { sum += $57 } END { print sum }","input_text":"a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,10","expected_output":"0\n","validation_input":"a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,5\na,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,15","validation_output":"0\n","family":"real-stackoverflow","difficulty":3,"split":"train","source":"stackoverflow-accepted-answer","license":"CC-BY-SA-4.0","question_url":"https://stackoverflow.com/questions/28905083/how-to-sum-a-column-in-awk","question_title":"How to Sum a column in AWK?","question_owner":"Ajo","answer_owner":"mpromonet","answer_id":28905292,"question_score":69}
25
+ {"id":"so-2957094","request":"Print all lines where the second whitespace-separated field is exactly the string LINUX.","program":"$2 == \"LINUX\" { print }","input_text":"1 LINUX param1 value1\n2 LINUXparam2 value2\n3 SOLARIS param3 value3\n4 SOLARIS param4 value4","expected_output":"1 LINUX param1 value1\n","validation_input":"10 LINUX test data\n20 LINUXX test data\n30 WINDOWS test data","validation_output":"10 LINUX test data\n","family":"real-stackoverflow","difficulty":3,"split":"train","source":"stackoverflow-accepted-answer","license":"CC-BY-SA-4.0","question_url":"https://stackoverflow.com/questions/2957094/how-to-use-awk-to-print-lines-where-a-field-matches-a-specific-string","question_title":"How to use awk to print lines where a field matches a specific string?","question_owner":"yael","answer_owner":"Hank Gay","answer_id":2957225,"question_score":71}
26
+ {"id":"so-2961635","request":"Write an awk program that removes the first two fields from each input line and prints the remaining content, preserving the original spacing between the remaining fields.","program":"{$1=$2=\"\"; print $0}","input_text":"! path/to/file.c another/path\nM src/main.c","expected_output":" another/path\n \n","validation_input":"? docs/readme.txt\nA lib/utils.h extra info here","validation_output":" \n extra info here\n","family":"real-stackoverflow","difficulty":3,"split":"train","source":"stackoverflow-accepted-answer","license":"CC-BY-SA-4.0","question_url":"https://stackoverflow.com/questions/2961635/using-awk-to-print-all-columns-from-the-nth-to-the-last","question_title":"Using awk to print all columns from the nth to the last","question_owner":"Andy","answer_owner":"zed_0xff","answer_id":2961994,"question_score":486}
27
+ {"id":"so-3080693","request":"Print only the last line of the input text.","program":"{ line = $0 } END { print line }","input_text":"First line\nSecond line\nThird line","expected_output":"Third line\n","validation_input":"Alpha\nBeta\nGamma\nDelta","validation_output":"Delta\n","family":"real-stackoverflow","difficulty":3,"split":"train","source":"stackoverflow-accepted-answer","license":"CC-BY-SA-4.0","question_url":"https://stackoverflow.com/questions/3080693/print-the-last-line-of-a-file-from-the-cli","question_title":"Print the last line of a file, from the CLI","question_owner":"yael","answer_owner":"Joey","answer_id":3080722,"question_score":70}
28
+ {"id":"so-38972736","request":"Print all lines from stdin that fall between the pattern 'PAT1' and 'PAT2', inclusive of both patterns. If multiple blocks exist, print all of them.","program":"/PAT1/,/PAT2/","input_text":"1\n2\nPAT1\n3 - first block\n4\nPAT2\n5\n6\nPAT1\n7 - second block\nPAT2\n8","expected_output":"PAT1\n3 - first block\n4\nPAT2\nPAT1\n7 - second block\nPAT2\n","validation_input":"START\nPAT1\nA\nB\nPAT2\nEND\nPAT1\nC\nPAT2","validation_output":"PAT1\nA\nB\nPAT2\nPAT1\nC\nPAT2\n","family":"real-stackoverflow","difficulty":3,"split":"train","source":"stackoverflow-accepted-answer","license":"CC-BY-SA-4.0","question_url":"https://stackoverflow.com/questions/38972736/how-to-print-lines-between-two-patterns-inclusive-or-exclusive-in-sed-awk-or","question_title":"How to print lines between two patterns, inclusive or exclusive (in sed, AWK or Perl)?","question_owner":"fedorqui","answer_owner":"fedorqui","answer_id":38972737,"question_score":116}
29
+ {"id":"so-4198138","request":"Reorder each line of a space-separated table by moving the first field to the end, preserving the order of the remaining fields.","program":"{first=$1; $1=\"\"; sub(/^ /, \"\"); print $0, first}","input_text":"AE United Arab Emirates","expected_output":"United Arab Emirates AE\n","validation_input":"AG Antigua & Barbuda\nUS United States of America","validation_output":"Antigua & Barbuda AG\nUnited States of America US\n","family":"real-stackoverflow","difficulty":3,"split":"train","source":"stackoverflow-accepted-answer","license":"CC-BY-SA-4.0","question_url":"https://stackoverflow.com/questions/4198138/printing-everything-except-the-first-field-with-awk","question_title":"Printing everything except the first field with awk","question_owner":"cfischer","answer_owner":"Ben Jackson","answer_id":4198169,"question_score":161}
30
+ {"id":"so-4304917","request":"Print the last two columns of each line.","program":"{ print $(NF-1), $NF }","input_text":"a b c d e\n1 2 3\nx y","expected_output":"d e\n2 3\nx y\n","validation_input":"one two three four\nalpha beta gamma\ncol1 col2","validation_output":"three four\nbeta gamma\ncol1 col2\n","family":"real-stackoverflow","difficulty":3,"split":"train","source":"stackoverflow-accepted-answer","license":"CC-BY-SA-4.0","question_url":"https://stackoverflow.com/questions/4304917/how-to-print-last-two-columns-using-awk","question_title":"How to print last two columns using awk","question_owner":"vehomzzz","answer_owner":"codaddict","answer_id":4304949,"question_score":126}
31
+ {"id":"so-5081916","request":"Read lines from stdin and print all fields starting from the 9th field to the end of the line, separated by spaces. If there are fewer than 9 fields, print an empty line.","program":"{ s = \"\"; for (i = 9; i <= NF; i++) s = s (s ? \" \" : \"\") $i; print s }","input_text":"1 2 3 4 5 6 7 8 9 10 11\na b c d e f g h i j k l m n","expected_output":"9 10 11\ni j k l m n\n","validation_input":"one two three four five six seven eight nine ten\ntwo four six eight ten twelve fourteen sixteen eighteen twenty","validation_output":"nine ten\neighteen twenty\n","family":"real-stackoverflow","difficulty":3,"split":"train","source":"stackoverflow-accepted-answer","license":"CC-BY-SA-4.0","question_url":"https://stackoverflow.com/questions/5081916/how-to-print-all-the-columns-after-a-particular-number-using-awk","question_title":"How to print all the columns after a particular number using awk?","question_owner":"Lazer","answer_owner":"Amadan","answer_id":5082055,"question_score":116}
32
+ {"id":"so-5374239","request":"Read tab-separated values from stdin. Replace the third field with the string 'REPLACED' and print the modified line, ensuring fields remain separated by tabs.","program":"BEGIN { FS = \"\\t\"; OFS = \"\\t\" } { $3 = \"REPLACED\"; print }","input_text":"LOAD_SETTLED\tLOAD_INIT\t2011-01-13 03:50:01\nSTATUS_OK\tSTATUS_PENDING\t2011-02-14 12:00:00","expected_output":"LOAD_SETTLED\tLOAD_INIT\tREPLACED\nSTATUS_OK\tSTATUS_PENDING\tREPLACED\n","validation_input":"COL_A\tCOL_B\tCOL_C\tCOL_D\nVAL_1\tVAL_2\tVAL_3\tVAL_4","validation_output":"COL_A\tCOL_B\tREPLACED\tCOL_D\nVAL_1\tVAL_2\tREPLACED\tVAL_4\n","family":"real-stackoverflow","difficulty":3,"split":"train","source":"stackoverflow-accepted-answer","license":"CC-BY-SA-4.0","question_url":"https://stackoverflow.com/questions/5374239/tab-separated-values-in-awk","question_title":"Tab separated values in awk","question_owner":"shantanuo","answer_owner":"glenn jackman","answer_id":5376527,"question_score":118}
33
+ {"id":"so-5536018","request":"Print only the specific field from each line that exactly matches the string 'yyy'.","program":"{for(i=1;i<=NF;i++){if($i==\"yyy\"){print $i}}}","input_text":"xxx yyy zzz\naaa bbb ccc\nyyy ddd eee\nfff ggg yyy","expected_output":"yyy\nyyy\nyyy\n","validation_input":"hello world foo\nbar yyy baz\nqux yyy","validation_output":"yyy\nyyy\n","family":"real-stackoverflow","difficulty":3,"split":"train","source":"stackoverflow-accepted-answer","license":"CC-BY-SA-4.0","question_url":"https://stackoverflow.com/questions/5536018/how-to-print-matched-regex-pattern-using-awk","question_title":"How to print matched regex pattern using awk?","question_owner":"marverix","answer_owner":"kurumi","answer_id":5536068,"question_score":170}
34
+ {"id":"so-6022384","request":"Print the 5th line of the input text.","program":"NR==5{print;exit}","input_text":"Line one\nLine two\nLine three\nLine four\nLine five\nLine six","expected_output":"Line five\n","validation_input":"Alpha\nBeta\nGamma\nDelta\nEpsilon","validation_output":"Epsilon\n","family":"real-stackoverflow","difficulty":3,"split":"train","source":"stackoverflow-accepted-answer","license":"CC-BY-SA-4.0","question_url":"https://stackoverflow.com/questions/6022384/bash-tool-to-get-nth-line-from-a-file","question_title":"Bash tool to get nth line from a file","question_owner":"Vlad Vivdovitch","answer_owner":"anubhava","answer_id":6022431,"question_score":914}
35
+ {"id":"so-8009664","request":"Split the input string by the pipe character '|' and print the resulting fields in reverse order, separated by spaces.","program":"{ n = split($0, a, \"|\"); for (i = n; i >= 1; i--) printf \"%s%s\", a[i], (i > 1 ? \" \" : \"\\n\") }","input_text":"12|23|11","expected_output":"11 23 12\n","validation_input":"A|B|C|D","validation_output":"D C B A\n","family":"real-stackoverflow","difficulty":3,"split":"train","source":"stackoverflow-accepted-answer","license":"CC-BY-SA-4.0","question_url":"https://stackoverflow.com/questions/8009664/how-to-split-a-delimited-string-into-an-array-in-awk","question_title":"How to split a delimited string into an array in awk?","question_owner":"Mohamed Saligh","answer_owner":"Calin Paul Alexandru","answer_id":8009724,"question_score":274}
36
+ {"id":"so-8786634","request":"Read lines from stdin and print the number of characters in each line.","program":"{ print length }","input_text":"Hello World\nShort\nThis is a longer sentence.","expected_output":"11\n5\n26\n","validation_input":"abc\n12345\n","validation_output":"3\n5\n","family":"real-stackoverflow","difficulty":3,"split":"train","source":"stackoverflow-accepted-answer","license":"CC-BY-SA-4.0","question_url":"https://stackoverflow.com/questions/8786634/how-to-print-the-number-of-characters-in-each-line-of-a-text-file","question_title":"How to print the number of characters in each line of a text file","question_owner":"vikas368","answer_owner":"Fred Foo","answer_id":8786674,"question_score":116}
37
+ {"id":"so-9351902","request":"Count the number of whitespace-separated fields in each line of the input.","program":"{ print NF }","input_text":"hello world\nfoo bar baz\nsingle","expected_output":"2\n3\n1\n","validation_input":"one two three four\nalpha beta","validation_output":"4\n2\n","family":"real-stackoverflow","difficulty":3,"split":"train","source":"stackoverflow-accepted-answer","license":"CC-BY-SA-4.0","question_url":"https://stackoverflow.com/questions/9351902/how-can-i-get-the-length-of-an-array-in-awk","question_title":"How can I get the length of an array in awk?","question_owner":"softghost","answer_owner":"shellter","answer_id":9351954,"question_score":79}
38
+ {"id":"so-9591744","request":"Append the string ' anotherthing' to the end of any line that starts with 'all:'. Print all lines, modified or not.","program":"/^all:/ { $0 = $0 \" anotherthing\" }\n{ print }","input_text":"somestuff...\nall: thing otherthing\nsome other stuff","expected_output":"somestuff...\nall: thing otherthing anotherthing\nsome other stuff\n","validation_input":"start\nall: foo bar\nend","validation_output":"start\nall: foo bar anotherthing\nend\n","family":"real-stackoverflow","difficulty":3,"split":"train","source":"stackoverflow-accepted-answer","license":"CC-BY-SA-4.0","question_url":"https://stackoverflow.com/questions/9591744/how-to-add-to-the-end-of-lines-containing-a-pattern-with-sed-or-awk","question_title":"How to add to the end of lines containing a pattern with sed or awk?","question_owner":"yasar","answer_owner":"user219882","answer_id":9591835,"question_score":98}
39
+ {"id":"so-9605232","request":"Merge every two consecutive lines of input into a single line, separated by a space.","program":"NR%2{printf \"%s \",$0;next;}1","input_text":"KEY 4048:1736 string\n3\nKEY 0:1772 string\n1","expected_output":"KEY 4048:1736 string 3\nKEY 0:1772 string 1\n","validation_input":"Line A\nLine B\nLine C\nLine D","validation_output":"Line A Line B\nLine C Line D\n","family":"real-stackoverflow","difficulty":3,"split":"train","source":"stackoverflow-accepted-answer","license":"CC-BY-SA-4.0","question_url":"https://stackoverflow.com/questions/9605232/how-to-merge-every-two-lines-into-one-from-the-command-line","question_title":"How to merge every two lines into one from the command line?","question_owner":"shantanuo","answer_owner":"Kent","answer_id":9605559,"question_score":229}
40
+ {"id":"so-22190902-p1","request":"Output the initial field from the very first line of the input.","program":"NR==1{print $1; exit}","input_text":"SUSE Linux Enterprise Server 11 (x86_64)\nVERSION = 11\nPATCHLEVEL = 2","expected_output":"SUSE\n","validation_input":"Hello World Test\nSecond Line Data\nThird Line Info","validation_output":"Hello\n","family":"real-stackoverflow","difficulty":3,"split":"train","source":"openrouter-paraphrase","license":"CC-BY-SA-4.0","question_url":"https://stackoverflow.com/questions/22190902/cut-or-awk-command-to-print-first-field-of-first-row","question_title":"cut or awk command to print first field of first row","question_owner":"user3331975","answer_owner":"devnull","answer_id":22190928,"question_score":114,"paraphrase_of":"so-22190902","paraphrase_model":"qwen/qwen3.7-plus"}
41
+ {"id":"so-2310605-p1","request":"Strip leading spaces and tabs from every line in the input text.","program":"{ sub(/^[ \\t]+/, \"\"); print }","input_text":" for (i = 0; i < 100; i++)\n\tfor (i = 0; i < 100; i++)\n \t for (i = 0; i < 100; i++)","expected_output":"for (i = 0; i < 100; i++)\nfor (i = 0; i < 100; i++)\nfor (i = 0; i < 100; i++)\n","validation_input":"\t\tindented line\n mixed spaces and tabs\nno indent","validation_output":"indented line\nmixed spaces and tabs\nno indent\n","family":"real-stackoverflow","difficulty":3,"split":"train","source":"openrouter-paraphrase","license":"CC-BY-SA-4.0","question_url":"https://stackoverflow.com/questions/2310605/how-to-remove-leading-whitespace-from-each-line-in-a-file","question_title":"How to remove leading whitespace from each line in a file","question_owner":"Lazer","answer_owner":"shuvalov","answer_id":2310620,"question_score":83,"paraphrase_of":"so-2310605","paraphrase_model":"qwen/qwen3.7-plus"}
42
+ {"id":"so-2626274-p1","request":"Display all fields starting from the fourth one, keeping the original whitespace between them intact.","program":"{ sub(/([^ ]+ +){3}/, \"\"); print }","input_text":"1 2 3 4 5 6 7\na b c d e f g h\n10 20 30 40","expected_output":"1 2 3 4 5 6 7\na b c d e f g h\n10 20 30 40\n","validation_input":"first second third fourth fifth\n1 2 3 4 5 6\nx y z w","validation_output":"first second third fourth fifth\n1 2 3 4 5 6\nx y z w\n","family":"real-stackoverflow","difficulty":3,"split":"train","source":"openrouter-paraphrase","license":"CC-BY-SA-4.0","question_url":"https://stackoverflow.com/questions/2626274/print-all-but-the-first-three-columns","question_title":"Print all but the first three columns","question_owner":"hhh","answer_owner":"olibre","answer_id":18817331,"question_score":125,"paraphrase_of":"so-2626274","paraphrase_model":"qwen/qwen3.7-plus"}
43
+ {"id":"so-2702564-p1","request":"Compute and output the total sum of all numbers listed in the input, assuming each number is on its own line.","program":"{ sum += $1 } END { print sum }","input_text":"34\n42\n11\n6\n2\n99","expected_output":"194\n","validation_input":"10\n20\n30","validation_output":"60\n","family":"real-stackoverflow","difficulty":3,"split":"train","source":"openrouter-paraphrase","license":"CC-BY-SA-4.0","question_url":"https://stackoverflow.com/questions/2702564/how-can-i-quickly-sum-all-numbers-in-a-file","question_title":"How can I quickly sum all numbers in a file?","question_owner":"Mark Roberts","answer_owner":"brian d foy","answer_id":2702614,"question_score":275,"paraphrase_of":"so-2702564","paraphrase_model":"qwen/qwen3.7-plus"}
44
+ {"id":"so-27028928-p1","request":"Join the first two fields of each line with a single space and print the combined result.","program":"{print $1 \" \" $2}","input_text":"hello how are you\ni am fine thanks","expected_output":"hello how\ni am\n","validation_input":"foo bar baz\nalpha beta gamma","validation_output":"foo bar\nalpha beta\n","family":"real-stackoverflow","difficulty":3,"split":"train","source":"openrouter-paraphrase","license":"CC-BY-SA-4.0","question_url":"https://stackoverflow.com/questions/27028928/awk-concatenate-two-string-variable-and-assign-to-a-third","question_title":"awk - concatenate two string variable and assign to a third","question_owner":"user3738926","answer_owner":"fedorqui","answer_id":27028953,"question_score":108,"paraphrase_of":"so-27028928","paraphrase_model":"qwen/qwen3.7-plus"}
45
+ {"id":"so-28905083-p1","request":"Calculate and print the sum of the 57th comma-separated field across all lines in the input.","program":"BEGIN { FS=\",\"; sum=0 } { sum += $57 } END { print sum }","input_text":"a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,10","expected_output":"0\n","validation_input":"a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,5\na,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,15","validation_output":"0\n","family":"real-stackoverflow","difficulty":3,"split":"train","source":"original-grammar-copy","license":"CC-BY-SA-4.0","question_url":"https://stackoverflow.com/questions/28905083/how-to-sum-a-column-in-awk","question_title":"How to Sum a column in AWK?","question_owner":"Ajo","answer_owner":"mpromonet","answer_id":28905292,"question_score":69,"paraphrase_of":"so-28905083","paraphrase_model":"qwen/qwen3.7-plus"}
46
+ {"id":"so-17001849-p1","request":"Output only those lines where the third field includes the substring 'snow'.","program":"$3 ~ /snow/ { print }","input_text":"C1 C2 C3\n1 a snow\n2 b snowman\nsnow c sowman","expected_output":"1 a snow\n2 b snowman\n","validation_input":"id name description\n1 test snowflake\n2 demo ice\n3 alpha snow","validation_output":"1 test snowflake\n3 alpha snow\n","family":"real-stackoverflow","difficulty":3,"split":"train","source":"openrouter-paraphrase","license":"CC-BY-SA-4.0","question_url":"https://stackoverflow.com/questions/17001849/awk-partly-string-match-if-column-word-partly-matches","question_title":"awk partly string match (if column/word partly matches)","question_owner":"pogibas","answer_owner":"Ahmed Masud","answer_id":17001897,"question_score":126,"paraphrase_of":"so-17001849","paraphrase_model":"qwen/qwen3.7-plus"}
47
+ {"id":"so-17988756-p1","request":"Retrieve and display all lines situated strictly between markers containing 'abc' and 'mno', omitting the marker lines themselves, while processing multiple such pairs across the file.","program":"/abc/{flag=1;next}/mno/{flag=0}flag","input_text":"abc\ndef1\nghi1\njkl1\nmno\nabc\ndef2\nghi2","expected_output":"def1\nghi1\njkl1\ndef2\nghi2\n","validation_input":"start\nabc\nline A\nline B\nmno\nend\nabc\nline C\nmno","validation_output":"line A\nline B\nline C\n","family":"real-stackoverflow","difficulty":3,"split":"train","source":"openrouter-paraphrase","license":"CC-BY-SA-4.0","question_url":"https://stackoverflow.com/questions/17988756/how-to-select-lines-between-two-marker-patterns-which-may-occur-multiple-times-w","question_title":"How to select lines between two marker patterns which may occur multiple times with awk/sed","question_owner":"dvai","answer_owner":"fedorqui","answer_id":17988834,"question_score":170,"paraphrase_of":"so-17988756","paraphrase_model":"qwen/qwen3.7-plus"}
48
+ {"id":"so-19149731-p1","request":"Compute the mean of the values in the second column and output it as 'Average: <value>'.","program":"{ sum += $2 } END { if (NR > 0) print \"Average: \" sum / NR }","input_text":"Alice 10\nBob 20\nCharlie 30","expected_output":"Average: 20\n","validation_input":"Item1 5.5\nItem2 4.5\nItem3 10","validation_output":"Average: 6.66667\n","family":"real-stackoverflow","difficulty":3,"split":"train","source":"openrouter-paraphrase","license":"CC-BY-SA-4.0","question_url":"https://stackoverflow.com/questions/19149731/use-awk-to-find-average-of-a-column","question_title":"Use awk to find average of a column","question_owner":"Ben Zifkin","answer_owner":"imp25","answer_id":19150191,"question_score":83,"paraphrase_of":"so-19149731","paraphrase_model":"qwen/qwen3.7-plus"}
49
+ {"id":"so-20600982-p1","request":"Create an awk script that processes comma-separated input from stdin: for lines with commas, trim leading and trailing whitespace from the second field only, then print the first field, a comma, and the cleaned second field; skip lines lacking commas.","program":"BEGIN{FS=\",\"; OFS=\",\"} /,/{gsub(/^[ \\t]+/,\"\",$2); gsub(/[ \\t]+$/,\"\",$2); print $1,$2}","input_text":"Name, Order\nTrim, working\ncat,cat1","expected_output":"Name,Order\nTrim,working\ncat,cat1\n","validation_input":"ID , Value\n 123 , 456 \nNoCommaHere","validation_output":"ID ,Value\n 123 ,456\n","family":"real-stackoverflow","difficulty":3,"split":"train","source":"openrouter-paraphrase","license":"CC-BY-SA-4.0","question_url":"https://stackoverflow.com/questions/20600982/trim-leading-and-trailing-spaces-from-a-string-in-awk","question_title":"Trim leading and trailing spaces from a string in awk","question_owner":"Marjer","answer_owner":"Floris","answer_id":20601021,"question_score":78,"paraphrase_of":"so-20600982","paraphrase_model":"qwen/qwen3.7-plus"}
50
+ {"id":"so-20752043-p1","request":"Prepend each input line with its zero-indexed line number and a comma, starting the count at 0 for the first line.","program":"{ print NR-1 \",\" $0 }","input_text":"line one\nline two\nline three","expected_output":"0,line one\n1,line two\n2,line three\n","validation_input":"hello\nworld","validation_output":"0,hello\n1,world\n","family":"real-stackoverflow","difficulty":3,"split":"train","source":"openrouter-paraphrase","license":"CC-BY-SA-4.0","question_url":"https://stackoverflow.com/questions/20752043/print-line-numbers-starting-at-zero-using-awk","question_title":"Print line numbers starting at zero using awk","question_owner":"user790049","answer_owner":"Lance Roberts","answer_id":20752092,"question_score":87,"paraphrase_of":"so-20752043","paraphrase_model":"qwen/qwen3.7-plus"}
51
+ {"id":"so-2096490-p1","request":"Display the penultimate field from every input line.","program":"{print $(NF-1)}","input_text":"one two three four\nalpha beta gamma","expected_output":"three\nbeta\n","validation_input":"a b c\nd e f g h","validation_output":"b\ng\n","family":"real-stackoverflow","difficulty":3,"split":"train","source":"openrouter-paraphrase","license":"CC-BY-SA-4.0","question_url":"https://stackoverflow.com/questions/2096490/print-second-to-last-column-field-in-awk","question_title":"Print second-to-last column/field in `awk`","question_owner":"Brian G","answer_owner":"Chris Kannon","answer_id":2096526,"question_score":225,"paraphrase_of":"so-2096490","paraphrase_model":"qwen/qwen3.7-plus"}
52
+ {"id":"so-1444406-p1","request":"Deduplicate the input lines, keeping only the first instance of each while maintaining the original sequence.","program":"!seen[$0]++","input_text":"apple\nbanana\napple\ncherry\nbanana\ndate","expected_output":"apple\nbanana\ncherry\ndate\n","validation_input":"line1\nline2\nline1\nline3\nline2\nline4","validation_output":"line1\nline2\nline3\nline4\n","family":"real-stackoverflow","difficulty":3,"split":"train","source":"openrouter-paraphrase","license":"CC-BY-SA-4.0","question_url":"https://stackoverflow.com/questions/1444406/how-to-delete-duplicate-lines-in-a-file-without-sorting-it-in-unix","question_title":"How to delete duplicate lines in a file without sorting it in Unix","question_owner":"Vijay","answer_owner":"Jonas Elfstr&#246;m","answer_id":1444448,"question_score":214,"paraphrase_of":"so-1444406","paraphrase_model":"qwen/qwen3.7-plus"}
53
+ {"id":"so-14462529-p1","request":"For every line in the input, output only its initial 22 characters.","program":"{ print substr($0, 1, 22) }","input_text":"000000000001199998000180000 DUMMY RAG # MFR NOT ST 1999980 ZZ- 0 0 0ZZ-\n000000000002199998000180000 DUMMY RAG # MFR NOT ST 1999980 ZZ- 0 0 0ZZ-","expected_output":"0000000000011999980001\n0000000000021999980001\n","validation_input":"ABCDEFGHIJKL1234567890EXTRA\nShort","validation_output":"ABCDEFGHIJKL1234567890\nShort\n","family":"real-stackoverflow","difficulty":3,"split":"train","source":"openrouter-paraphrase","license":"CC-BY-SA-4.0","question_url":"https://stackoverflow.com/questions/14462529/how-to-get-first-n-characters-of-each-line-in-unix-data-file","question_title":"How to get first n characters of each line in unix data file","question_owner":"Teja","answer_owner":"Chris Seymour","answer_id":14462614,"question_score":82,"paraphrase_of":"so-14462529","paraphrase_model":"qwen/qwen3.7-plus"}
54
+ {"id":"so-14739057-p1","request":"Output the third field for any line where the eighth field matches \"ClNonZ\" exactly.","program":"$8 == \"ClNonZ\" { print $3 }","input_text":"2 14 0.180467091 0.800424628 0 0.0566 0.0103 ClNonZ\n5 22 0.010615711 0.959660297 0.010615711 0.0476 0.0061 ClNonZ\n9 31 0.492569002 0.350318471 0.138004246 0.0485 0.0088 ClNonZ","expected_output":"0.180467091\n0.010615711\n0.492569002\n","validation_input":"1 11 0.959660297 0 0.021231423 -0.0073 -0.0031 MhZisp\n3 19 0.98089172 0 0 -0.0158 0.0124 MhNonZ\n2 14 0.180467091 0.800424628 0 0.0566 0.0103 ClNonZ","validation_output":"0.180467091\n","family":"real-stackoverflow","difficulty":3,"split":"train","source":"openrouter-paraphrase","license":"CC-BY-SA-4.0","question_url":"https://stackoverflow.com/questions/14739057/using-awk-with-column-value-conditions","question_title":"using awk with column value conditions","question_owner":"user1687130","answer_owner":"Rob Davis","answer_id":14739101,"question_score":137,"paraphrase_of":"so-14739057","paraphrase_model":"qwen/qwen3.7-plus"}
55
+ {"id":"so-1506521-p1","request":"Display the third field from line 5 of the input.","program":"NR==5{print $3; exit}","input_text":"Line1 F1 F2 F3 F4\nLine2 F1 F2 F3 F4\nLine3 F1 F2 F3 F4\nLine4 F1 F2 F3 F4\nLine5 F1 F2 TargetValue F4","expected_output":"F2\n","validation_input":"A B C D E\n1 2 3 4 5\na b c d e\nx y z w v\np q r s t","validation_output":"r\n","family":"real-stackoverflow","difficulty":3,"split":"train","source":"openrouter-paraphrase","license":"CC-BY-SA-4.0","question_url":"https://stackoverflow.com/questions/1506521/select-row-and-element-in-awk","question_title":"Select row and element in awk","question_owner":"Tim","answer_owner":"Dennis Williamson","answer_id":1506601,"question_score":108,"paraphrase_of":"so-1506521","paraphrase_model":"qwen/qwen3.7-plus"}
56
+ {"id":"so-15681498-p1","request":"Compute the mean of all whitespace-delimited numbers in the input and print it as 'ave: <value>' using standard float precision.","program":"{s+=$1} END{if(NR>0) print \"ave:\", s/NR}","input_text":"1.00 1.23 54.4 213.2 3.4","expected_output":"ave: 1\n","validation_input":"10 20 30","validation_output":"ave: 10\n","family":"real-stackoverflow","difficulty":3,"split":"train","source":"openrouter-paraphrase","license":"CC-BY-SA-4.0","question_url":"https://stackoverflow.com/questions/15681498/scripts-for-computing-the-average-of-a-list-of-numbers-in-a-data-file","question_title":"Scripts for computing the average of a list of numbers in a data file","question_owner":"JackWM","answer_owner":"Chris Seymour","answer_id":15681543,"question_score":64,"paraphrase_of":"so-15681498","paraphrase_model":"qwen/qwen3.7-plus"}
57
+ {"id":"so-16136943-p1","request":"Extract the second column from each line of input, where the first column is a number and the second column is a double-quoted string that may contain spaces. The output should be just the quoted string.","program":"{ match($0, /\"[^\"]*\"/); print substr($0, RSTART, RLENGTH) }","input_text":"1540 \"A B\"\n6 \"C\"\n119 \"D\"","expected_output":"\"A B\"\n\"C\"\n\"D\"\n","validation_input":"100 \"Hello World\"\n200 \"Test\"\n300 \"Foo Bar Baz\"","validation_output":"\"Hello World\"\n\"Test\"\n\"Foo Bar Baz\"\n","family":"real-stackoverflow","difficulty":3,"split":"train","source":"original-grammar-copy","license":"CC-BY-SA-4.0","question_url":"https://stackoverflow.com/questions/16136943/how-can-i-get-the-second-column-from-command-output","question_title":"How can I get the second column from command output?","question_owner":"Qiang Xu","answer_owner":"catay","answer_id":16137100,"question_score":276,"paraphrase_of":"so-16136943","paraphrase_model":"qwen/qwen3.7-plus"}
58
+ {"id":"so-1068650-p1","request":"Create an awk script that strips the UTF-8 Byte Order Mark (bytes EF BB BF) from the start of the first input line if present, and then prints every line.","program":"NR==1{sub(/^\\xef\\xbb\\xbf/,\"\")}1","input_text":"Hello World\nSecond Line\nThird Line","expected_output":"Hello World\nSecond Line\nThird Line\n","validation_input":"No BOM Here\nAnother Line","validation_output":"No BOM Here\nAnother Line\n","family":"real-stackoverflow","difficulty":3,"split":"train","source":"openrouter-paraphrase","license":"CC-BY-SA-4.0","question_url":"https://stackoverflow.com/questions/1068650/using-awk-to-remove-the-byte-order-mark","question_title":"Using awk to remove the Byte-order mark","question_owner":"Boldewyn","answer_owner":"Bartosz","answer_id":1068700,"question_score":107,"paraphrase_of":"so-1068650","paraphrase_model":"qwen/qwen3.7-plus"}
59
+ {"id":"so-11952854-p1","request":"Develop an awk program that processes stdin by splitting each line into whitespace-delimited fields. For any field containing an '@', separate it into a key and value; if the value is empty or only spaces, set it to 'Y'. Output each resulting pair as 'key=value' on its own line, maintaining the original input order.","program":"{\n for (i = 1; i <= NF; i++) {\n if (index($i, \"@\") > 0) {\n n = split($i, parts, \"@\")\n key = parts[1]\n val = \"\"\n for (j = 2; j <= n; j++) {\n if (j > 2) val = val \"@\"\n val = val parts[j]\n }\n if (val ~ /^[[:space:]]*$/) {\n val = \"Y\"\n }\n print key \"=\" val\n }\n }\n}","input_text":"user@john admin@\nhost@server1 config@ \ndata@value","expected_output":"user=john\nadmin=Y\nhost=server1\nconfig=Y\ndata=value\n","validation_input":"a@ b@ \nc@d e@f","validation_output":"a=Y\nb=Y\nc=d\ne=f\n","family":"real-stackoverflow","difficulty":3,"split":"train","source":"openrouter-paraphrase","license":"CC-BY-SA-4.0","question_url":"https://stackoverflow.com/questions/11952854/how-to-check-if-the-variable-value-in-awk-script-is-null-or-empty","question_title":"How to check if the variable value in AWK script is null or empty?","question_owner":"samarth","answer_owner":"Levon","answer_id":11952924,"question_score":64,"paraphrase_of":"so-11952854","paraphrase_model":"qwen/qwen3.7-plus"}
60
+ {"id":"so-11967776-p1","request":"Exchange the positions of the first and second whitespace-separated fields in each input line while keeping the remainder of the line intact.","program":"{ temp = $1; $1 = $2; $2 = temp; print }","input_text":"Affy-id chr 0 pos NA06984\nCol1 Col2 Rest of line","expected_output":"chr Affy-id 0 pos NA06984\nCol2 Col1 Rest of line\n","validation_input":"A B C D E\nFirst Second Third","validation_output":"B A C D E\nSecond First Third\n","family":"real-stackoverflow","difficulty":3,"split":"train","source":"openrouter-paraphrase","license":"CC-BY-SA-4.0","question_url":"https://stackoverflow.com/questions/11967776/swap-two-columns-awk-sed-python-perl","question_title":"Swap two columns - awk, sed, python, perl","question_owner":"Charley Farley","answer_owner":"perreal","answer_id":11967849,"question_score":83,"paraphrase_of":"so-11967776","paraphrase_model":"qwen/qwen3.7-plus"}
61
+ {"id":"so-12204192-p1","request":"Extract the third path component, the fifth path component, and the value after the equals sign from each line. Use forward slashes and equals signs as delimiters.","program":"BEGIN { FS = \"[/=]\" } { print $3, $5, $8 }","input_text":"/logs/tc0001/tomcat/tomcat7.1/conf/catalina.properties:app.env.server.name = demo.example.com\n/logs/tc0001/tomcat/tomcat7.2/conf/catalina.properties:app.env.server.name = quest.example.com","expected_output":"tc0001 tomcat7.1 demo.example.com\ntc0001 tomcat7.2 quest.example.com\n","validation_input":"/data/projA/src/main/java/App.java:version = 1.0.0\n/data/projB/lib/utils/helper.py:mode = production","validation_output":"projA main 1.0.0\nprojB utils \n","family":"real-stackoverflow","difficulty":3,"split":"train","source":"original-grammar-copy","license":"CC-BY-SA-4.0","question_url":"https://stackoverflow.com/questions/12204192/using-multiple-delimiters-in-awk","question_title":"Using multiple delimiters in awk","question_owner":"Satish","answer_owner":"embedded.kyle","answer_id":12204350,"question_score":306,"paraphrase_of":"so-12204192","paraphrase_model":"qwen/qwen3.7-plus"}
62
+ {"id":"so-12297859-p1","request":"Write an awk utility that reads from stdin and outputs only the portion of each line following the final colon; if no colon exists, output the whole line.","program":"{idx=match($0, /:[^:]*$/); if(idx>0) print substr($0, idx+1); else print $0}","input_text":"TF_list_to_test10004/Nus_k0.345_t0.1_e0.1.adj:PKMYT1\npath/to/file:GENE_A\nno_colon_here","expected_output":"PKMYT1\nGENE_A\nno_colon_here\n","validation_input":"server:port:service_name\nsimple_line\nkey:value","validation_output":"service_name\nsimple_line\nvalue\n","family":"real-stackoverflow","difficulty":3,"split":"train","source":"openrouter-paraphrase","license":"CC-BY-SA-4.0","question_url":"https://stackoverflow.com/questions/12297859/remove-all-text-before-colon","question_title":"Remove all text before colon","question_owner":"NewUsr_stat","answer_owner":"Sacha Epskamp","answer_id":12297934,"question_score":77,"paraphrase_of":"so-12297859","paraphrase_model":"qwen/qwen3.7-plus"}
63
+ {"id":"so-13046167-p1","request":"Output the final field for every input line that includes the substring 'A1'.","program":"/A1/ {print $NF}","input_text":"A1 123 456\nB1 234 567\nC1 345 678\nA1 098 766\nB1 987 6545\nC1 876 5434","expected_output":"456\n766\n","validation_input":"A1 foo bar\nX1 ignore this\nA1 baz qux\nY1 skip me","validation_output":"bar\nqux\n","family":"real-stackoverflow","difficulty":3,"split":"train","source":"openrouter-paraphrase","license":"CC-BY-SA-4.0","question_url":"https://stackoverflow.com/questions/13046167/printing-the-last-column-of-a-line-in-a-file","question_title":"Printing the last column of a line in a file","question_owner":"Rayne","answer_owner":"Olaf Dietsche","answer_id":13046224,"question_score":201,"paraphrase_of":"so-13046167","paraphrase_model":"qwen/qwen3.7-plus"}
64
+ {"id":"so-2957094-p1","request":"Output every line whose second whitespace-delimited field matches the exact string LINUX.","program":"$2 == \"LINUX\" { print }","input_text":"1 LINUX param1 value1\n2 LINUXparam2 value2\n3 SOLARIS param3 value3\n4 SOLARIS param4 value4","expected_output":"1 LINUX param1 value1\n","validation_input":"10 LINUX test data\n20 LINUXX test data\n30 WINDOWS test data","validation_output":"10 LINUX test data\n","family":"real-stackoverflow","difficulty":3,"split":"train","source":"openrouter-paraphrase","license":"CC-BY-SA-4.0","question_url":"https://stackoverflow.com/questions/2957094/how-to-use-awk-to-print-lines-where-a-field-matches-a-specific-string","question_title":"How to use awk to print lines where a field matches a specific string?","question_owner":"yael","answer_owner":"Hank Gay","answer_id":2957225,"question_score":71,"paraphrase_of":"so-2957094","paraphrase_model":"qwen/qwen3.7-plus"}
65
+ {"id":"so-2961635-p1","request":"Create an awk script that strips the first two fields from each line and outputs the rest, maintaining the original spacing between the remaining fields.","program":"{$1=$2=\"\"; print $0}","input_text":"! path/to/file.c another/path\nM src/main.c","expected_output":" another/path\n \n","validation_input":"? docs/readme.txt\nA lib/utils.h extra info here","validation_output":" \n extra info here\n","family":"real-stackoverflow","difficulty":3,"split":"train","source":"openrouter-paraphrase","license":"CC-BY-SA-4.0","question_url":"https://stackoverflow.com/questions/2961635/using-awk-to-print-all-columns-from-the-nth-to-the-last","question_title":"Using awk to print all columns from the nth to the last","question_owner":"Andy","answer_owner":"zed_0xff","answer_id":2961994,"question_score":486,"paraphrase_of":"so-2961635","paraphrase_model":"qwen/qwen3.7-plus"}
66
+ {"id":"so-3080693-p1","request":"Display only the final line of the input text.","program":"{ line = $0 } END { print line }","input_text":"First line\nSecond line\nThird line","expected_output":"Third line\n","validation_input":"Alpha\nBeta\nGamma\nDelta","validation_output":"Delta\n","family":"real-stackoverflow","difficulty":3,"split":"train","source":"openrouter-paraphrase","license":"CC-BY-SA-4.0","question_url":"https://stackoverflow.com/questions/3080693/print-the-last-line-of-a-file-from-the-cli","question_title":"Print the last line of a file, from the CLI","question_owner":"yael","answer_owner":"Joey","answer_id":3080722,"question_score":70,"paraphrase_of":"so-3080693","paraphrase_model":"qwen/qwen3.7-plus"}
67
+ {"id":"so-38972736-p1","request":"Extract and print all lines from stdin located between the patterns 'PAT1' and 'PAT2', including the lines containing these patterns, for every occurrence in the input.","program":"/PAT1/,/PAT2/","input_text":"1\n2\nPAT1\n3 - first block\n4\nPAT2\n5\n6\nPAT1\n7 - second block\nPAT2\n8","expected_output":"PAT1\n3 - first block\n4\nPAT2\nPAT1\n7 - second block\nPAT2\n","validation_input":"START\nPAT1\nA\nB\nPAT2\nEND\nPAT1\nC\nPAT2","validation_output":"PAT1\nA\nB\nPAT2\nPAT1\nC\nPAT2\n","family":"real-stackoverflow","difficulty":3,"split":"train","source":"openrouter-paraphrase","license":"CC-BY-SA-4.0","question_url":"https://stackoverflow.com/questions/38972736/how-to-print-lines-between-two-patterns-inclusive-or-exclusive-in-sed-awk-or","question_title":"How to print lines between two patterns, inclusive or exclusive (in sed, AWK or Perl)?","question_owner":"fedorqui","answer_owner":"fedorqui","answer_id":38972737,"question_score":116,"paraphrase_of":"so-38972736","paraphrase_model":"qwen/qwen3.7-plus"}
68
+ {"id":"so-4198138-p1","request":"Reorder each line of a space-separated table by moving the first field to the end, preserving the order of the remaining fields.","program":"{first=$1; $1=\"\"; sub(/^ /, \"\"); print $0, first}","input_text":"AE United Arab Emirates","expected_output":"United Arab Emirates AE\n","validation_input":"AG Antigua & Barbuda\nUS United States of America","validation_output":"Antigua & Barbuda AG\nUnited States of America US\n","family":"real-stackoverflow","difficulty":3,"split":"train","source":"original-grammar-copy","license":"CC-BY-SA-4.0","question_url":"https://stackoverflow.com/questions/4198138/printing-everything-except-the-first-field-with-awk","question_title":"Printing everything except the first field with awk","question_owner":"cfischer","answer_owner":"Ben Jackson","answer_id":4198169,"question_score":161,"paraphrase_of":"so-4198138","paraphrase_model":"qwen/qwen3.7-plus"}
69
+ {"id":"so-4304917-p1","request":"Output the last two columns for every line.","program":"{ print $(NF-1), $NF }","input_text":"a b c d e\n1 2 3\nx y","expected_output":"d e\n2 3\nx y\n","validation_input":"one two three four\nalpha beta gamma\ncol1 col2","validation_output":"three four\nbeta gamma\ncol1 col2\n","family":"real-stackoverflow","difficulty":3,"split":"train","source":"openrouter-paraphrase","license":"CC-BY-SA-4.0","question_url":"https://stackoverflow.com/questions/4304917/how-to-print-last-two-columns-using-awk","question_title":"How to print last two columns using awk","question_owner":"vehomzzz","answer_owner":"codaddict","answer_id":4304949,"question_score":126,"paraphrase_of":"so-4304917","paraphrase_model":"qwen/qwen3.7-plus"}
70
+ {"id":"so-9351902-p1","request":"For every line in the input, determine and output the count of fields delimited by whitespace.","program":"{ print NF }","input_text":"hello world\nfoo bar baz\nsingle","expected_output":"2\n3\n1\n","validation_input":"one two three four\nalpha beta","validation_output":"4\n2\n","family":"real-stackoverflow","difficulty":3,"split":"train","source":"openrouter-paraphrase","license":"CC-BY-SA-4.0","question_url":"https://stackoverflow.com/questions/9351902/how-can-i-get-the-length-of-an-array-in-awk","question_title":"How can I get the length of an array in awk?","question_owner":"softghost","answer_owner":"shellter","answer_id":9351954,"question_score":79,"paraphrase_of":"so-9351902","paraphrase_model":"qwen/qwen3.7-plus"}
71
+ {"id":"so-9591744-p1","request":"Output all lines from the input; if a line begins with 'all:', append ' anotherthing' to its end before printing.","program":"/^all:/ { $0 = $0 \" anotherthing\" }\n{ print }","input_text":"somestuff...\nall: thing otherthing\nsome other stuff","expected_output":"somestuff...\nall: thing otherthing anotherthing\nsome other stuff\n","validation_input":"start\nall: foo bar\nend","validation_output":"start\nall: foo bar anotherthing\nend\n","family":"real-stackoverflow","difficulty":3,"split":"train","source":"openrouter-paraphrase","license":"CC-BY-SA-4.0","question_url":"https://stackoverflow.com/questions/9591744/how-to-add-to-the-end-of-lines-containing-a-pattern-with-sed-or-awk","question_title":"How to add to the end of lines containing a pattern with sed or awk?","question_owner":"yasar","answer_owner":"user219882","answer_id":9591835,"question_score":98,"paraphrase_of":"so-9591744","paraphrase_model":"qwen/qwen3.7-plus"}
72
+ {"id":"so-9605232-p1","request":"Combine each pair of adjacent input lines into one line, using a space as the separator.","program":"NR%2{printf \"%s \",$0;next;}1","input_text":"KEY 4048:1736 string\n3\nKEY 0:1772 string\n1","expected_output":"KEY 4048:1736 string 3\nKEY 0:1772 string 1\n","validation_input":"Line A\nLine B\nLine C\nLine D","validation_output":"Line A Line B\nLine C Line D\n","family":"real-stackoverflow","difficulty":3,"split":"train","source":"openrouter-paraphrase","license":"CC-BY-SA-4.0","question_url":"https://stackoverflow.com/questions/9605232/how-to-merge-every-two-lines-into-one-from-the-command-line","question_title":"How to merge every two lines into one from the command line?","question_owner":"shantanuo","answer_owner":"Kent","answer_id":9605559,"question_score":229,"paraphrase_of":"so-9605232","paraphrase_model":"qwen/qwen3.7-plus"}
73
+ {"id":"so-5081916-p1","request":"Read lines from stdin and print all fields starting from the 9th field to the end of the line, separated by spaces. If there are fewer than 9 fields, print an empty line.","program":"{ s = \"\"; for (i = 9; i <= NF; i++) s = s (s ? \" \" : \"\") $i; print s }","input_text":"1 2 3 4 5 6 7 8 9 10 11\na b c d e f g h i j k l m n","expected_output":"9 10 11\ni j k l m n\n","validation_input":"one two three four five six seven eight nine ten\ntwo four six eight ten twelve fourteen sixteen eighteen twenty","validation_output":"nine ten\neighteen twenty\n","family":"real-stackoverflow","difficulty":3,"split":"train","source":"original-grammar-copy","license":"CC-BY-SA-4.0","question_url":"https://stackoverflow.com/questions/5081916/how-to-print-all-the-columns-after-a-particular-number-using-awk","question_title":"How to print all the columns after a particular number using awk?","question_owner":"Lazer","answer_owner":"Amadan","answer_id":5082055,"question_score":116,"paraphrase_of":"so-5081916","paraphrase_model":"qwen/qwen3.7-plus"}
74
+ {"id":"so-5374239-p1","request":"Read tab-separated values from stdin. Replace the third field with the string 'REPLACED' and print the modified line, ensuring fields remain separated by tabs.","program":"BEGIN { FS = \"\\t\"; OFS = \"\\t\" } { $3 = \"REPLACED\"; print }","input_text":"LOAD_SETTLED\tLOAD_INIT\t2011-01-13 03:50:01\nSTATUS_OK\tSTATUS_PENDING\t2011-02-14 12:00:00","expected_output":"LOAD_SETTLED\tLOAD_INIT\tREPLACED\nSTATUS_OK\tSTATUS_PENDING\tREPLACED\n","validation_input":"COL_A\tCOL_B\tCOL_C\tCOL_D\nVAL_1\tVAL_2\tVAL_3\tVAL_4","validation_output":"COL_A\tCOL_B\tREPLACED\tCOL_D\nVAL_1\tVAL_2\tREPLACED\tVAL_4\n","family":"real-stackoverflow","difficulty":3,"split":"train","source":"original-grammar-copy","license":"CC-BY-SA-4.0","question_url":"https://stackoverflow.com/questions/5374239/tab-separated-values-in-awk","question_title":"Tab separated values in awk","question_owner":"shantanuo","answer_owner":"glenn jackman","answer_id":5376527,"question_score":118,"paraphrase_of":"so-5374239","paraphrase_model":"qwen/qwen3.7-plus"}
75
+ {"id":"so-5536018-p1","request":"For every input line, identify and print the specific field that is an exact match for the string 'yyy'.","program":"{for(i=1;i<=NF;i++){if($i==\"yyy\"){print $i}}}","input_text":"xxx yyy zzz\naaa bbb ccc\nyyy ddd eee\nfff ggg yyy","expected_output":"yyy\nyyy\nyyy\n","validation_input":"hello world foo\nbar yyy baz\nqux yyy","validation_output":"yyy\nyyy\n","family":"real-stackoverflow","difficulty":3,"split":"train","source":"openrouter-paraphrase","license":"CC-BY-SA-4.0","question_url":"https://stackoverflow.com/questions/5536018/how-to-print-matched-regex-pattern-using-awk","question_title":"How to print matched regex pattern using awk?","question_owner":"marverix","answer_owner":"kurumi","answer_id":5536068,"question_score":170,"paraphrase_of":"so-5536018","paraphrase_model":"qwen/qwen3.7-plus"}
76
+ {"id":"so-6022384-p1","request":"Output the fifth line from the provided input text.","program":"NR==5{print;exit}","input_text":"Line one\nLine two\nLine three\nLine four\nLine five\nLine six","expected_output":"Line five\n","validation_input":"Alpha\nBeta\nGamma\nDelta\nEpsilon","validation_output":"Epsilon\n","family":"real-stackoverflow","difficulty":3,"split":"train","source":"openrouter-paraphrase","license":"CC-BY-SA-4.0","question_url":"https://stackoverflow.com/questions/6022384/bash-tool-to-get-nth-line-from-a-file","question_title":"Bash tool to get nth line from a file","question_owner":"Vlad Vivdovitch","answer_owner":"anubhava","answer_id":6022431,"question_score":914,"paraphrase_of":"so-6022384","paraphrase_model":"qwen/qwen3.7-plus"}
77
+ {"id":"so-8009664-p1","request":"Divide the input string using '|' as the delimiter and display the resulting segments in reverse order, joined by spaces.","program":"{ n = split($0, a, \"|\"); for (i = n; i >= 1; i--) printf \"%s%s\", a[i], (i > 1 ? \" \" : \"\\n\") }","input_text":"12|23|11","expected_output":"11 23 12\n","validation_input":"A|B|C|D","validation_output":"D C B A\n","family":"real-stackoverflow","difficulty":3,"split":"train","source":"openrouter-paraphrase","license":"CC-BY-SA-4.0","question_url":"https://stackoverflow.com/questions/8009664/how-to-split-a-delimited-string-into-an-array-in-awk","question_title":"How to split a delimited string into an array in awk?","question_owner":"Mohamed Saligh","answer_owner":"Calin Paul Alexandru","answer_id":8009724,"question_score":274,"paraphrase_of":"so-8009664","paraphrase_model":"qwen/qwen3.7-plus"}
78
+ {"id":"so-8786634-p1","request":"Read each line from stdin and output its character count.","program":"{ print length }","input_text":"Hello World\nShort\nThis is a longer sentence.","expected_output":"11\n5\n26\n","validation_input":"abc\n12345\n","validation_output":"3\n5\n","family":"real-stackoverflow","difficulty":3,"split":"train","source":"openrouter-paraphrase","license":"CC-BY-SA-4.0","question_url":"https://stackoverflow.com/questions/8786634/how-to-print-the-number-of-characters-in-each-line-of-a-text-file","question_title":"How to print the number of characters in each line of a text file","question_owner":"vikas368","answer_owner":"Fred Foo","answer_id":8786674,"question_score":116,"paraphrase_of":"so-8786634","paraphrase_model":"qwen/qwen3.7-plus"}
paraphrase_data.py ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import concurrent.futures
5
+ import json
6
+ import os
7
+ import re
8
+ import time
9
+ import urllib.error
10
+ import urllib.request
11
+ from pathlib import Path
12
+
13
+ MODEL = "qwen/qwen3.7-plus"
14
+ NUMBER_PATTERN = re.compile(r"(?<![A-Za-z_])\d+(?:\.\d+)?(?![A-Za-z_])")
15
+ LITERAL_PATTERN = re.compile(r'"([^"\n]+)"')
16
+
17
+
18
+ def literals_to_preserve(row: dict) -> list[str]:
19
+ values = []
20
+ for value in LITERAL_PATTERN.findall(row["program"]):
21
+ if "\\" in value or "%" in value or value in {" ", ",", "\\t"}:
22
+ continue
23
+ if len(value) >= 2:
24
+ values.append(value)
25
+ values.extend(re.findall(r"/\^?([A-Z][A-Z0-9 _-]{1,})/", row["program"]))
26
+ return sorted(set(values))
27
+
28
+
29
+ def number_aliases(number: int) -> set[str]:
30
+ units = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]
31
+ teens = ["ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"]
32
+ tens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]
33
+ if number < 10:
34
+ words = units[number]
35
+ elif number < 20:
36
+ words = teens[number - 10]
37
+ elif number < 100:
38
+ words = tens[number // 10] + ("-" + units[number % 10] if number % 10 else "")
39
+ elif number < 120:
40
+ remainder = number % 100
41
+ tail = units[remainder] if remainder < 10 else teens[remainder - 10]
42
+ words = "one hundred" + (" " + tail if remainder else "")
43
+ else:
44
+ words = str(number)
45
+ ordinals = {
46
+ 0: "zeroth", 1: "first", 2: "second", 3: "third", 4: "fourth",
47
+ 5: "fifth", 6: "sixth", 7: "seventh", 8: "eighth", 9: "ninth",
48
+ 10: "tenth", 11: "eleventh", 12: "twelfth", 13: "thirteenth",
49
+ 14: "fourteenth", 15: "fifteenth", 16: "sixteenth", 17: "seventeenth",
50
+ 18: "eighteenth", 19: "nineteenth", 20: "twentieth", 30: "thirtieth",
51
+ 40: "fortieth", 50: "fiftieth",
52
+ 60: "sixtieth", 70: "seventieth", 80: "eightieth", 90: "ninetieth",
53
+ 100: "one hundredth",
54
+ }
55
+ if number in ordinals:
56
+ ordinal = ordinals[number]
57
+ elif number < 100:
58
+ ordinal = tens[number // 10] + "-" + ordinals[number % 10]
59
+ else:
60
+ ordinal = str(number)
61
+ return {str(number), words, words.replace("-", " "), ordinal, ordinal.replace("-", " ")}
62
+
63
+
64
+ def valid_paraphrase(original: str, paraphrase: str, row: dict) -> bool:
65
+ paraphrase = paraphrase.strip()
66
+ if not 10 <= len(paraphrase) <= 400 or paraphrase == original.strip():
67
+ return False
68
+ if "\n" in paraphrase or "```" in paraphrase:
69
+ return False
70
+ lowered = paraphrase.lower()
71
+ for value in set(NUMBER_PATTERN.findall(original)):
72
+ aliases = number_aliases(int(value)) if value.isdigit() else {value}
73
+ if not any(re.search(r"(?<![a-z0-9])" + re.escape(alias) + r"(?![a-z0-9])", lowered) for alias in aliases):
74
+ return False
75
+ if any(value not in paraphrase for value in literals_to_preserve(row)):
76
+ return False
77
+ for marker in ("comma-separated", "tab-separated", "first appearance", "two decimal places"):
78
+ if marker in original.lower() and marker not in lowered:
79
+ synonyms = {
80
+ "comma-separated": ("comma separated", "csv"),
81
+ "tab-separated": ("tab separated", "tsv"),
82
+ "first appearance": ("first appear", "order in which", "order they appear"),
83
+ "two decimal places": ("2 decimal places", "two decimals"),
84
+ }
85
+ if not any(term in lowered for term in synonyms[marker]):
86
+ return False
87
+ return True
88
+
89
+
90
+ def request_batch(batch: list[dict], timeout: int = 120) -> list[str]:
91
+ payload = {
92
+ "model": MODEL,
93
+ "messages": [
94
+ {
95
+ "role": "system",
96
+ "content": (
97
+ "You paraphrase technical text-processing requests. Return only valid JSON. "
98
+ "Preserve the exact operation, every numeric value as an Arabic numeral, all field "
99
+ "positions and names, literal values, input separator, output formatting, ordering, "
100
+ "and tie-breaking requirements. Do not add or remove constraints. Keep each request "
101
+ "concise and natural, and vary sentence structure. Keep every numeric value unchanged."
102
+ ),
103
+ },
104
+ {
105
+ "role": "user",
106
+ "content": "Return {\"paraphrases\": [...]} with exactly one paraphrase per numbered input, in order.\n"
107
+ + "\n".join(f"{index}. {row['request']}" for index, row in enumerate(batch, 1)),
108
+ },
109
+ ],
110
+ "response_format": {"type": "json_object"},
111
+ "temperature": 0.85,
112
+ "max_tokens": 3000,
113
+ "reasoning": {"enabled": False},
114
+ }
115
+ base_url = os.environ["OPENROUTER_BASE_URL"].rstrip("/")
116
+ request = urllib.request.Request(
117
+ base_url + "/chat/completions",
118
+ data=json.dumps(payload).encode("utf-8"),
119
+ headers={
120
+ "Authorization": "Bearer " + os.environ["OPENROUTER_API_KEY"],
121
+ "Content-Type": "application/json",
122
+ },
123
+ )
124
+ for attempt in range(4):
125
+ try:
126
+ with urllib.request.urlopen(request, timeout=timeout) as response:
127
+ data = json.load(response)
128
+ content = data["choices"][0]["message"]["content"]
129
+ parsed = json.loads(content)
130
+ paraphrases = parsed["paraphrases"]
131
+ if not isinstance(paraphrases, list) or len(paraphrases) != len(batch):
132
+ raise ValueError("Wrong paraphrase count")
133
+ return [str(value).strip() for value in paraphrases]
134
+ except (urllib.error.URLError, urllib.error.HTTPError, KeyError, ValueError, json.JSONDecodeError) as error:
135
+ if attempt == 3:
136
+ raise RuntimeError(f"Paraphrase request failed after retries: {error}") from error
137
+ time.sleep(2 ** attempt)
138
+ raise AssertionError("unreachable")
139
+
140
+
141
+ def main() -> None:
142
+ parser = argparse.ArgumentParser()
143
+ parser.add_argument("input", type=Path)
144
+ parser.add_argument("output", type=Path)
145
+ parser.add_argument("--batch-size", type=int, default=12)
146
+ parser.add_argument("--workers", type=int, default=16)
147
+ parser.add_argument("--limit", type=int)
148
+ args = parser.parse_args()
149
+
150
+ rows = [json.loads(line) for line in args.input.open(encoding="utf-8")]
151
+ rows.sort(key=lambda row: row["id"])
152
+ eligible = [row for row in rows if row["split"] == "train"]
153
+ if args.limit:
154
+ eligible = eligible[: args.limit]
155
+
156
+ existing_paraphrases = {}
157
+ if args.output.exists():
158
+ for line in args.output.open(encoding="utf-8"):
159
+ row = json.loads(line)
160
+ if row.get("paraphrase_of"):
161
+ existing_paraphrases[row["paraphrase_of"]] = row
162
+ batches = [eligible[index:index + args.batch_size] for index in range(0, len(eligible), args.batch_size)]
163
+ batches = [batch for batch in batches if any(row["id"] not in existing_paraphrases for row in batch)]
164
+
165
+ args.output.parent.mkdir(parents=True, exist_ok=True)
166
+ with args.output.open("w", encoding="utf-8") as handle:
167
+ for row in rows:
168
+ handle.write(json.dumps(row, ensure_ascii=False, separators=(",", ":")) + "\n")
169
+ for row in existing_paraphrases.values():
170
+ handle.write(json.dumps(row, ensure_ascii=False, separators=(",", ":")) + "\n")
171
+
172
+ accepted = 0
173
+ fallback = 0
174
+ completed = 0
175
+ with concurrent.futures.ThreadPoolExecutor(max_workers=args.workers) as executor:
176
+ futures = {executor.submit(request_batch, batch): batch for batch in batches}
177
+ for future in concurrent.futures.as_completed(futures):
178
+ batch = futures[future]
179
+ try:
180
+ paraphrases = future.result()
181
+ except Exception as error:
182
+ print(f"batch failed; retaining originals: {error}", flush=True)
183
+ paraphrases = [row["request"] for row in batch]
184
+ new_rows = []
185
+ for row, paraphrase in zip(batch, paraphrases):
186
+ if row["id"] in existing_paraphrases:
187
+ continue
188
+ new_row = dict(row)
189
+ new_row["id"] = row["id"] + "-p1"
190
+ new_row["paraphrase_of"] = row["id"]
191
+ new_row["paraphrase_model"] = MODEL
192
+ if valid_paraphrase(row["request"], paraphrase, row):
193
+ new_row["request"] = paraphrase
194
+ new_row["source"] = "openrouter-paraphrase"
195
+ accepted += 1
196
+ else:
197
+ new_row["source"] = "original-grammar-copy"
198
+ fallback += 1
199
+ new_rows.append(new_row)
200
+ with args.output.open("a", encoding="utf-8") as handle:
201
+ for row in new_rows:
202
+ handle.write(json.dumps(row, ensure_ascii=False, separators=(",", ":")) + "\n")
203
+ completed += len(batch)
204
+ if completed % 240 == 0 or completed == len(eligible):
205
+ print(f"paraphrased {completed}/{len(eligible)}; accepted={accepted}; guarded={fallback}", flush=True)
206
+ print(f"wrote {len(rows) + len(eligible)} rows to {args.output}; accepted={accepted}; guarded={fallback}")
207
+
208
+
209
+ if __name__ == "__main__":
210
+ main()
validate_dataset.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import collections
5
+ import concurrent.futures
6
+ import hashlib
7
+ import json
8
+ import shutil
9
+ import subprocess
10
+ from pathlib import Path
11
+
12
+ from awkweave.execution import run_awk
13
+
14
+
15
+ def awk_version() -> str:
16
+ executable = shutil.which("awk")
17
+ if executable is None:
18
+ return "awk unavailable"
19
+ for arguments in (["-W", "version"], ["--version"]):
20
+ result = subprocess.run([executable, *arguments], capture_output=True, text=True, check=False)
21
+ output = (result.stdout or result.stderr).strip().splitlines()
22
+ if result.returncode == 0 and output:
23
+ return output[0]
24
+ return "unknown awk"
25
+
26
+
27
+ def validate_row(row: dict) -> tuple[str, str | None]:
28
+ try:
29
+ if run_awk(row["program"], row["input_text"]) != row["expected_output"]:
30
+ return row["id"], "primary output mismatch"
31
+ if run_awk(row["program"], row["validation_input"]) != row["validation_output"]:
32
+ return row["id"], "validation output mismatch"
33
+ return row["id"], None
34
+ except Exception as error:
35
+ return row["id"], str(error)[:500]
36
+
37
+
38
+ def main() -> None:
39
+ parser = argparse.ArgumentParser()
40
+ parser.add_argument("data", type=Path)
41
+ parser.add_argument("--workers", type=int, default=8)
42
+ parser.add_argument("--output", type=Path)
43
+ args = parser.parse_args()
44
+ rows = [json.loads(line) for line in args.data.open(encoding="utf-8")]
45
+ ids = [row["id"] for row in rows]
46
+ if len(ids) != len(set(ids)):
47
+ raise ValueError("Duplicate row IDs")
48
+ by_id = {row["id"]: row for row in rows}
49
+ for row in rows:
50
+ if row.get("paraphrase_of"):
51
+ original = by_id.get(row["paraphrase_of"])
52
+ if original is None:
53
+ raise ValueError(f"Missing paraphrase source: {row['id']}")
54
+ for key in ("program", "input_text", "expected_output", "validation_input", "validation_output", "split"):
55
+ if row[key] != original[key]:
56
+ raise ValueError(f"Paraphrase changed {key}: {row['id']}")
57
+ if row["split"] != "train":
58
+ raise ValueError(f"Paraphrase outside train split: {row['id']}")
59
+
60
+ errors = []
61
+ with concurrent.futures.ProcessPoolExecutor(max_workers=args.workers) as executor:
62
+ for completed, (row_id, error) in enumerate(executor.map(validate_row, rows, chunksize=20), 1):
63
+ if error:
64
+ errors.append({"id": row_id, "error": error})
65
+ if completed % 5000 == 0:
66
+ print(f"validated {completed}/{len(rows)}", flush=True)
67
+ split_integrity = {}
68
+ for left, right in (
69
+ ("train", "validation"), ("train", "test"), ("validation", "test"),
70
+ ("train", "challenge"), ("validation", "challenge"), ("test", "challenge"),
71
+ ):
72
+ left_rows = [row for row in rows if row["split"] == left and not row.get("paraphrase_of")]
73
+ right_rows = [row for row in rows if row["split"] == right and not row.get("paraphrase_of")]
74
+ split_integrity[f"{left}-{right}"] = {
75
+ "input_overlap": len({row["input_text"] for row in left_rows} & {row["input_text"] for row in right_rows}),
76
+ "request_program_overlap": len(
77
+ {(row["request"], row["program"]) for row in left_rows}
78
+ & {(row["request"], row["program"]) for row in right_rows}
79
+ ),
80
+ }
81
+ summary = {
82
+ "data": str(args.data),
83
+ "sha256": hashlib.sha256(args.data.read_bytes()).hexdigest(),
84
+ "rows": len(rows),
85
+ "executions": len(rows) * 2,
86
+ "awk_version": awk_version(),
87
+ "errors": errors,
88
+ "splits": dict(collections.Counter(row["split"] for row in rows)),
89
+ "sources": dict(collections.Counter(row["source"] for row in rows)),
90
+ "families": dict(collections.Counter(row["family"] for row in rows)),
91
+ "unique_requests": len({row["request"] for row in rows}),
92
+ "unique_programs": len({row["program"] for row in rows}),
93
+ "split_integrity": split_integrity,
94
+ }
95
+ text = json.dumps(summary, indent=2)
96
+ if args.output:
97
+ args.output.write_text(text, encoding="utf-8")
98
+ print(text)
99
+ if errors:
100
+ raise SystemExit(1)
101
+
102
+
103
+ if __name__ == "__main__":
104
+ main()
validation.json ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "data": "awkweave-so-paraphrased.jsonl",
3
+ "sha256": "9007041bd618932757c8b63bce9e8fcbf30bda1d047ee43af41870e6f4ad10fb",
4
+ "rows": 78,
5
+ "executions": 156,
6
+ "awk_version": "mawk 1.3.4 20200120",
7
+ "errors": [],
8
+ "splits": {
9
+ "train": 78
10
+ },
11
+ "sources": {
12
+ "stackoverflow-accepted-answer": 39,
13
+ "openrouter-paraphrase": 33,
14
+ "original-grammar-copy": 6
15
+ },
16
+ "families": {
17
+ "real-stackoverflow": 78
18
+ },
19
+ "unique_requests": 72,
20
+ "unique_programs": 39,
21
+ "split_integrity": {
22
+ "train-validation": {
23
+ "input_overlap": 0,
24
+ "request_program_overlap": 0
25
+ },
26
+ "train-test": {
27
+ "input_overlap": 0,
28
+ "request_program_overlap": 0
29
+ },
30
+ "validation-test": {
31
+ "input_overlap": 0,
32
+ "request_program_overlap": 0
33
+ },
34
+ "train-challenge": {
35
+ "input_overlap": 0,
36
+ "request_program_overlap": 0
37
+ },
38
+ "validation-challenge": {
39
+ "input_overlap": 0,
40
+ "request_program_overlap": 0
41
+ },
42
+ "test-challenge": {
43
+ "input_overlap": 0,
44
+ "request_program_overlap": 0
45
+ }
46
+ }
47
+ }