0

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

Chris Taylor
  • 46,912
  • 15
  • 110
  • 154
Sumod
  • 3,806
  • 9
  • 50
  • 69
  • 1
    The awk is correct, it's the file that is the problem like @paxdiablo says, run `dos2unix file.csv` to sort out the line ending issue. Sidenote: drop the [UUoC](http://partmaps.org/era/unix/award.html). – Chris Seymour Sep 16 '13 at 09:13

2 Answers2

3

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.

Community
  • 1
  • 1
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
1

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

Fredrik Pihl
  • 44,604
  • 7
  • 83
  • 130