Slartibartfast Slartibartfast - 1 month ago 21
Linux Question

How to redirect out put of xargs when using sed

Since swiching over to a better management system I am wanting to remove all the redundant logs at the top of each of our source files. In Notepad++ I was able to achieve the result by using "replace in files" and replacing matches to

\A(//.*\n)+
with blank. On Linux however I am having no such luck and am needing to resort to 'xargs' and 'sed'.

The sed expression I'm using is:

sed '1,/^[^\/]/{/^[^\/]/b; d}'


Ugly to be sure but it does seem to work.

The problem I'm having is when I try to run that through 'xargs' in order to feed it all the source files in our system I am unable to redirect the output to 'stripped' files, which I then intend to copy over the originals.

I want something in the line of:

find . -name "*.com" -type f -print0 | xargs -0 -I file sed '1,/^[^\/]/{/^[^\/]/b; d}' "file" > "file.stripped"


However I'm having grief passing the ">" through to the receiving environment (shell) as I'm already using too many quote marks. I have tried all manner of escaping and shell "wrappers" but I just can't get it to play ball.

Anyone care to point me in the right direction?

Thanks,
Slarti.

Answer

I made a similar scenario with a simpler sed expression just as an example, see if it works for you:

I created 3 files with the string "abcd" inside each:

# ls -l
total 12
-rw-r--r-- 1 root root 5 Oct  6 09:05 test.aaaaa.com
-rw-r--r-- 1 root root 5 Oct  6 09:05 test2.aaaaa.com
-rw-r--r-- 1 root root 5 Oct  6 09:05 test3.aaaaa.com
# cat test*
abcd
abcd
abcd

Running the find command as you showed using the -exec option instead of xargs, and replacing the sed expression for a silly one that simply replaces every "a" for "b" and the option -i, that writes directly do the input file:

# find . -name "*.com" -type f -print0 -exec sed -i 's/a/b/g' {} \;
./test2.aaaaa.com./test3.aaaaa.com./test.aaaaa.com
# cat test*
bbcd
bbcd
bbcd

In your case it should look like this:

# find . -name "*.com" -type f -print0 -exec sed -i '1,/^[^\/]/{/^[^\/]/b; d}' {} \;
Comments