2

I have a file that has

click
css_add_violation_false

click
css_add_claim_false

and

select
css_driver1_birth_date_month
birth_date_month

select
css_driver1_birth_date_day
birth_date_day

How could I replace the click[newline]value with click(value)?
or click[newline]value[newline]value with click(value,value)

I couldn't figure it out with sed probably because it's not good for multi-line stuff.

I tried using tr to remove the carriage return with

tr 'select\n' 'select('

but that removed all the carriage returns and added lots of (

(note: osx)

Desired Output:

click(css_add_violation_false)
click(css_add_claim_false)

and

select(css_driver1_birth_date_month, birth_date_month)
select(css_driver1_birth_date_day, birth_date_day

Will be a good more general answer if it can handle any number of params until a blank line is seen.

  • desired/expected output added. Thanks. – Michael Durrant Aug 18 '15 at 12:30
  • Additional condition added at bottom. – Michael Durrant Aug 18 '15 at 12:35
3

With awk:

awk '{if($0=="click"){getline n;printf "%s(%s)\n", $0, n}else{print}}' file

If the line matches click, load the next line in a varable called n and then print the desired output format.

Edit:

If there is a variable number of multiple lines and you want to combine them until the empty line occures, use this:

awk '{if($0=="click"){getline n; printf "%s(%s", $0, n;
  while($0!=""){printf ",%s", $0; getline};
  printf ")\n\n", x}else{print}}' file

It prints the lines comma-separated, until it finds an empty line.

  • This is great! Is there any way it could handle multiple lines ? (see updated example) – Michael Durrant Aug 18 '15 at 12:34
  • How about: awk '{if($0=="select"){getline n;getline n2; printf "%s(%s, %s)\n", $0, n, n2}else{print}}' for the multi-line. Not sure how to combine the two. – Michael Durrant Aug 18 '15 at 12:54
  • @MichaelDurrant I edited the answer – chaos Aug 18 '15 at 13:20
0

perl is good tool for this job:

$ perl -p00e 's/click\n(.*)\n/click(\1)\n/' file
click(css_add_violation_false)

click(css_add_claim_false)
0

For GNU sed

sed -Ez 's/(click)\n([^\n]*)/\1(\2)/g'

or old-style

sed '/click/{N;s/\n/(/;s/$/)/;}'
  • thanks but -r not available on osx (tagged and noted in question) – Michael Durrant Aug 18 '15 at 12:42
  • @MichaelDurrant in OSX you can use -E – Costas Aug 18 '15 at 12:44
  • What's -z? It's defintely not on my version of GNU sed. Also your old version only puts the direct next line in brackets. – 123 Aug 18 '15 at 13:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.