Read input param and passs to sed with xargs

Solution for Read input param and passs to sed with xargs
is Given Below:

I have two files, file 1 and file 2: I want to add a log at the beginning of each function to know from which file it was executed:

File1:

function one(){
}

function two(){
}

File2:

function one(){
}

function two(){
}

I’m trying by listing the files, using xargs to send the file to sed to find the pattern and add the log after the match

ls  file*  | xargs sed  '/function /a $.log("File");'

output:

function one(){
$.log("File");
}

function two(){
$.log("File");
}

function one(){
$.log("File");
}

function two(){
$.log("File");
}

Now I need to use the filename as a variable inside sed, but in reviewing xargs --help and sed --help I don’t see how to solve this.

Is there a reference to the file that sed is processing that can be used within the command? Something like

ls  file*  | xargs sed  '/function /a $.log("$INPUT_REFERENCE");'

Expected output:

function one(){
$.log("File1");
}

function two(){
$.log("File1");
}
function one(){
$.log("File2");
}

function two(){
$.log("File2");
}

If you’re open to using awk:

awk '
1                                                 # print current line
$1=="function" { print "$.log(""FILENAME"");"   # print a $.log() line
}' File*

Or as a one-liner:

awk '1;$1=="function"{print "$.log(""FILENAME"");"}' File*

This generates the following for the 2 sample files:

function one(){
$.log("File1");
}

function two(){
$.log("File1");
}
function one(){
$.log("File2");
}

function two(){
$.log("File2");
}

Below code should implement what you need, although I don’t fully get the semantics of you’re trying to achieve, as function foo() code will get overridden by its next declaration (in the same file).
What you’re looking for is xargs’s -I <string>:

$ cat foo.sh
function one(){
}

function two(){
}

$ touch File{1..2}

$ ls File* | xargs [email protected] sed $'/function /a$.log("@");' foo.sh
function one(){
$.log("File1");
}

function two(){
$.log("File1");
}

function one(){
$.log("File2");
}

function two(){
$.log("File2");
}

Mind above uses GNU sed, if you’re using macosx you’ll need to use gsed there.

This might work for you (GNU sed & parallel):

parallel sed -i ''/function/a$.log("{}");'' {} ::: file[12]

Update in place file1 and file2, appending a line after the word function.