0

I have the following (simplified) script

#!/bin/bash

replace(){
    sed "s/$1/$2/g"
}

#first
replace "search" "replacement"
#second
replace "replacement" "again"

I want the second replace to work on the output of the first replace without reading them into a script variable so i can easily chain them further.

It works perfectly on the first pass, i assume i need to pipe or redirect the output of replace (sed) into stdin again so the second replace will be able to use it in its own sed.

Edit:

There will be an indefinite number of calls to replace and similar functions within the script. Piping the first two together does not resolve my issue as it does not scale or rather only works for a fixed number of calls.

Blob31
  • 71
  • 1
  • 6
  • 2
    Use a pipe: `replace a b | replace x y` – Socowi May 30 '18 at 12:39
  • Possible duplicate of [read stdin in function in bash script](https://stackoverflow.com/questions/14004756/read-stdin-in-function-in-bash-script) – kabanus May 30 '18 at 12:44
  • @shellter because i simplified too much ^^ I do not know how many calls to replace or similar functions will happen as that gets read from the command line. – Blob31 May 30 '18 at 14:37

2 Answers2

2

You can pipe them:

replace "search" "replacement" | replace "replacement" "again"

or:

replace "$(replace "search" "replacement")" "again"
Kokogino
  • 984
  • 1
  • 5
  • 17
0

You could use this and could pass N number of arguments to your script, no need to call multiple functions multiple times.

cat script.ksh
var=$(echo $@)
awk -v line="$var" 'BEGIN{num=split(line, array," ")} {for(i=1;i<=num;i+=2){sub(array[i],array[(i+1)])}} 1'  Input_file

Adding a non-one liner form of code too here.

cat script.ksh
var=$(echo $@)
awk -v line="$var" '
BEGIN{ num=split(line, array," ") }
{
  for(i=1;i<=num;i+=2){
   sub(array[i],array[(i+1)])}
}
1'  Input_file

Execution of code:

Let's say following is the Input_file

cat Input_file
t1 test2 test3
fwvwv wbvw4e314 211232
test1 test2 test3

Now after executing the above code as script.ksh following will be the output.

./script15.ksh test1 SINGH test2 KING
t1 KING test3
fwvwv wbvw4e314 211232
SINGH KING test3

So you could see test1 is substituted by SINGH and test2 with KING likewise we could do it for more.

RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93