Slartibartfast Slartibartfast - 5 months ago 44
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

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?



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
-rw-r--r-- 1 root root 5 Oct  6 09:05
-rw-r--r-- 1 root root 5 Oct  6 09:05
# cat test*

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' {} \;
# cat test*

In your case it should look like this:

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