Home > database >  How can I ignore whitespace when using a sedfile to make recursive changes in a directory?
How can I ignore whitespace when using a sedfile to make recursive changes in a directory?

Time:11-05

I have a directory consisting of 102 sub-directories with 1590 files. I attempted to run the below command recursively against all files, including files with whitespace in the name to change a list of 400 tags from #tag to [[link]].

find . -name '*.md' | xargs sed -i -f sedfile *.md

It works only for files that do not have whitespace in the file names. The sedfile is formatted as s/#tag/[[link]]/g

sed: can't read ./4.Programming/G-Code/List: No such file or directory
sed: can't read of: No such file or directory
sed: can't read Common: No such file or directory
sed: can't read G-Code: No such file or directory
sed: can't read Commands: No such file or directory
sed: can't read and: No such file or directory
sed: can't read What: No such file or directory
sed: can't read They: No such file or directory
sed: can't read Mean.md: No such file or directory

The file name is 4.Programming/G-Code/List of Common G-Code Commands and What They Mean.md.

I had previously used

find . -type f -name "*.md" -print0 | xargs -0 sed -i '' -e 's/#tag/[[link]]/g'

to make the changes individually, but I am not looking forward to manually changing 390 more.

When I attempt to combine these two

find . -name '*.md' print0 | xargs -0 sed -i -f sedfile *.md

I get

find: paths must precede expression: `print0`

The articles I have found thus far in my research show how to make multiple changes to a single file or a single change to multiple files. How can I edit either of the two examples to cover *.md files in the directory?

CodePudding user response:

There is a typo: you use print0 instead of -print0.

You also don't need the *.md, because xargs is providing the filenames.

This should work:

find . -name '*.md' -print0 | xargs -0 sed -i -f sedfile

You could also use -exec instead:

find . -name '*.md' -exec sed -i -f sedfile {}  
  • Related