Why the following code printing duplicate records?
bash-4.1$ cat rm1
c1 c2 c3
l1 2 3 4
l2 2 3 2
bash-4.1$ awk '{print $0} OFS = "\n"' rm1
c1 c2 c3
c1 c2 c3
l1 2 3 4
l1 2 3 4
l2 2 3 2
l2 2 3 2
The awk
script:
awk '{print $0} OFS = "\n"' file
can be more clearly written in this case as:
awk '
{print $0}
OFS = "\n"
' file
Since there is no condition on the line {print $0}
the action is performed for every input line. And, since the condition on the next line ( OFS = "\n"
) evaluates to a non-zero value for every line read, the default action ( {print $0}
) is also performed for every input line. Therefore, your script prints every line twice.
If you're trying to print each input field as a separate output line, you need to do something to cause the input line to be re-evaluated; perhaps you intended something like:
awk '{$1 = $1}1' OFS="\n" file
Note that the OFS="\n"
is outside the single quotes and the spaces around the equal sign have to be removed when using this form.
1 Like
@Akshay: Oh i have no problem with the code. However, I would like to understand the logic behind duplicate records.
@Don: Hi DOn, Thanks. Could you please explain the logic behind. Also how did you manage to put "small code tags" ?
'{$1 = $1}1'
Thanks but what about this ?
'{$1 = $1}1'
I'm not sure what you mean by "small code tags", but the button marked </>
at the far right at the top of your editing screen when editing or creating a new post produces ``` and ```
tags which use the same font and background color used by the
```text
and
```
tags, but do not force a line break.
1 Like