'Echo text to multiple files using find
I'd like to add some simple text into some files. Specifically, I do this on Linux lpfc drivers:
ls -1 /sys/class/scsi_host/host* | awk -F '@' '{system("echo 0x0 > "$1"/lpfc_log_verbose")}'
But thinking about common case I need to handle spaces in file names. Thus I turned to find:
find -L /sys/class/scsi_host -nowarn -maxdepth 2 -type f -name 'lpfc_log_verbose' -exec echo 0x0 > {} \; 2>/dev/null
But this seems not working.
find -L /sys/class/scsi_host -maxdepth 2 -type f -name 'lpfc_log_verbose' -exec cat {} \; 2>/dev/null
is fine but shows my edit didn't success. So can we use redirect in find -exec? What is the correct work-around?
Solution 1:[1]
How about this -
find -L /sys/class/scsi_host -nowarn -maxdepth 2 -type f -name 'lpfc_log_verbose' |
while read -r filename; do
echo "0x0" > "$filename"
done
or
while read -r filename; do
echo "0x0" > "$filename"
done < <(find -L /sys/class/scsi_host -nowarn -maxdepth 2 -type f -name 'lpfc_log_verbose')
Since echo is a shell built-in you cannot use it directly with -exec. However, you can do the following -
find -L /sys/class/scsi_host -nowarn -maxdepth 2 -type f -name 'lpfc_log_verbose' -exec sh -c 'echo "0x0" > {}' \;
Solution 2:[2]
An easy way to do this is to have the to_be_written content written to a temporary/dummy file and use cp to copy the content to the destination file, inside exec.
Use cp instead of echo.
cp gets interpreted correctly while echo gets enumerated a little different and hence fails to work.
{} inside -exec replaces each filename found by find.
echo 1 > /tmp/dummy
find /sys/kernel/debug/tracing -name enable -exec cp /tmp/dummy {} \;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
