Reputation: 3846
I want to enclose each line of my input in square brackets. I am able to add the beginning square bracket. But not the ending one. The ending "]" goes to the next line and clips the line.
e.g. - Here is my script -
cat file.csv | awk 'BEGIN {FS=","; OFS=","} {print $1,"["$6,$7"]"}'
The op is - ]ABC,[CD,EF
Thanks
Upvotes: 0
Views: 3992
Reputation: 882326
It looks like this may be a line-ending issue, as in your lines are terminated with CR/LF
(carriage return and line feed) rather than just LF
on its own. What's actually being output is:
ABC,[CD,EF<CR>]
and the CR
is forcing the cursor back to the start of the line before outputting the final ]
character.
You can see a similar effect with:
pax> awk -v x='abcdef^M' 'END {print "123 ["x"]"}' </dev/null
]23 [abcdef
where the ^M
is actually a CR
character, input with CTRL-V
, CTRL-M
.
As to how to fix it, you can either fix the file itself to get rid of the dodgy line endings, or you can use something like gsub
on the final field of the line to get rid of CR
characters:
pax> # this bit here ----------vvvvvvvvvvvvvvvv
pax> awk -v x='abcdef^M' 'END {gsub("^M","",x);print "123 ["x"]"}' </dev/null
123 [abcdef]
In your case, that would be:
awk 'BEGIN {FS=","; OFS=","} {gsub("^M","",$7);print $1,"["$6,$7"]"}' file.csv
noting that cat file.csv |
is totally unnecessary here since awk
is perfectly capable of processing file names itself. Myself, I'd prefer fixing the file if that's at all possible.
Fow a multitude of ways to fix said file (depending on what tools you have available to you), see this excellent answer.
Upvotes: 3
Reputation: 45670
Your code works with proper input, example:
$ echo {A..J} | sed 's/ /,/g' | awk 'BEGIN {FS=","; OFS=","} {print $1,"["$6,$7"]"}'
A,[F,G]
as the migthy @paxdiablo says, probably a line-ending issue. Check with the file
-command
To convert to proper line-endings use e.g. fromdos
or dos2unix
Upvotes: 1