1

I have a file temp.txt. Here I wanted to replace comma (,) with || between Select and From keywords.

select emp_name,
       emp_id,
       loc
from   emp_join ,
       emp_loc
where emp_join.id = emp_loc.id 
and  join_date > to_date('2015-01-01','YYYY-MM-DD')

UNION

select emp_name,
       emp_id,
       loc
from   emp_term,
       emp_loc
where  emp_term.id = emp_loc.id
and   term_date = to_date('2015-01-01','YYYY-MM-DD'); 

I am using the sed command

sed 's/,/||/g' temp.txt

but its replacing all comma in the file.

Is there a simple unix command that will allow me to do this? How to do it using sed?

2
  • @Rakesh Sharma command edited sed -e '/^select/,/loc/s/,/||/'
    – c4f4t0r
    Mar 30, 2017 at 9:34
  • What does the loc do here?
    – Ramy
    Jun 29, 2022 at 4:32

3 Answers 3

2
sed -e '/^select/,/^from/s/,/||/' temp.txt
1
  • Rakesh, when I am executing the command given by you, its replacing all commas present in the file. Wanted to replace the comma between Select and From keyword only.
    – Ashish Mri
    Mar 30, 2017 at 2:39
0
root@admin:~# cat N | sed 's/\(.\+\)\,\(.\+\)/\1\|\|\2/g'
select emp_name,
       emp_id,
       loc
from   emp_join ,
       emp_loc
where emp_join.id = emp_loc.id 
and  join_date > to_date('2015-01-01'||'YYYY-MM-DD')

UNION

select emp_name,
       emp_id,
       loc
from   emp_term,
       emp_loc
where  emp_term.id = emp_loc.id
and   term_date = to_date('2015-01-01'||'YYYY-MM-DD'); 
1
  • When I am using the above command - cat temp.txt | sed 's/(.\+)\,(.\+)/\1\|\|\2/g' - its replacing comma present in To_date function. join_date > to_date('2015-01-01'||'YYYY-MM-DD')
    – Ashish Mri
    Mar 30, 2017 at 2:42
0

With perl:

perl -0777 -pe 's{\bselect\b.*?\bfrom\b}{$& =~ s/,/||/g}esig' < temp.txt

Would replace , with || between every select word and the next from word following it, case insensitively (so allowing both from and From for instance as in your question, but also FROM, FrOm...). We use the \b word boundary operators around those words, so it wouldn't match on the from in fromage for instance, but it would match in from,age or from-age or "from" as ,, - and " are not word characters.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .