1

I use ack very often, but something I have not been able to discover is how to make it add new lines when using the output parameter.

Example

echo 'name=Joe,id=123' | ack '^name=(\w+),id=(\d+)' --output="User name: $1\nUser ID: $2"

I expect

User name: Joe
User ID: 123

but I get

User name: Joe\nUser ID: 123

Anyway to make ack respect the new lines characters in the output?

Thanks

ikegami
  • 367,544
  • 15
  • 269
  • 518
JohnnyLoo
  • 877
  • 1
  • 11
  • 22

2 Answers2

3

You are passing \n to ack instead of a newline. Replace

--output='User name: $1\nUser ID: $2'

with

--output='User name: $1
User ID: $2'

or

--output="$( printf 'User name: $1\nUser ID: $2' )"

or

--output=$'User name: $1\nUser ID: $2'                   # bash
ikegami
  • 367,544
  • 15
  • 269
  • 518
2

You can put arbitrary code into that string via @{[ … ]} interpolation. For some reason a literal "\n" string won't work, but chr 0x0A or $/ does.

Example:

$ echo a b | ack '(\w+)\s+(\w+)' --output '$1@{[ chr 0x0A ]}$2'

Output:

a
b

Note that this kind of functionality is likely to break in the future, see also discussions like https://github.com/beyondgrep/ack2/issues/531

amon
  • 57,091
  • 2
  • 89
  • 149
  • 2
    Author of ack here. `@{[ … ]}` is absolutely not going to work in ack 3, currently under development. It's too dangerous. We've severely limited what can be done with `--output`. – Andy Lester Sep 23 '17 at 17:34