-2

In Linux I'm trying to find a file in a directory, backup it with another name and, then, replace it with another one.

I tried the first two actions with these commands

find foldername -name filename.html; -exec sed -i .bak;

but it's says

bash: -exec: command not found

Inian
  • 80,270
  • 14
  • 142
  • 161
Sergio Gandrus
  • 139
  • 1
  • 12
  • 2
    Why do you put a semicolon after the file name? A semicolon tells bash that one command ended and another is about to start, and `-exec` is not a command bash recognizes. If you really need the semicolon there, you have to put the file name in quotes, or escape it. [See also this question](https://stackoverflow.com/questions/20913198/why-are-the-backslash-and-semicolon-required-with-the-find-commands-exec-optio). – Karsten Koop Jun 08 '18 at 10:25
  • Oh, right! I tried semicolon after I tried pipe to connect the two commands :) – Sergio Gandrus Jun 08 '18 at 10:42
  • `;` separates two commands. It makes `bash` search the `-exec` program and `bash` fails (with the error message you posted). Don't put `;` in the command line unless you need to write two commands (not here). The command you put after `-exec` needs to be terminated with `\;`. This tells `find` where the arguments of `-exec` end and allows it to look for more options in the rest of the command line. – axiac Jun 08 '18 at 10:47
  • Possible duplicate of [Recursively rename files using find and sed](https://stackoverflow.com/questions/4793892/recursively-rename-files-using-find-and-sed) – jww Jun 08 '18 at 15:21

2 Answers2

1

Try this:

find foldername -name filename.html -exec cp -vp {}{,.bak} \; -exec truncate -s 0 {} \;

This uses find's exec option like it looks like you tried to use. Then cp copies the file (specified with {}) and appends .bak to the copy and preserves what it can with the p option:

preserve the specified attributes (default: mode,ownership,timestamps), if possible additional attributes: context, links, xattr, all

This leaves the original file in place as well.

Brandon Miller
  • 4,695
  • 1
  • 20
  • 27
-1

You can do the following:

find . -name 'FILE_PATTERN_HERE' | xargs -I file_name cp file_name file_name.bkp

You can pipe the output of find command to cp using xargs. Here file_name acts as the output of find.

Example

find . -name 'logback.xml*'

Output:

./logback.xml
./apache-cassandra-3.11.1/conf/logback.xml

After running the command

find . -name 'logback.xml*' | xargs -I file_name cp file_name file_name.bkp
find . -name 'logback.xml*'

Output:

./logback.xml
./apache-cassandra-3.11.1/conf/logback.xml
./apache-cassandra-3.11.1/conf/logback.xml.bkp
./logback.xml.bkp
pkgajulapalli
  • 1,066
  • 3
  • 20
  • 44