[英]BASH find and replace in all files in directory using FIND and SED
我需要查找並替換目錄中所有文件的某些字符串,包括子目錄。 我想我幾乎可以使用以下方法說明我的一般方法。 我在-exec內部進行的工作不僅僅限於此替換,但為清楚起見已將其刪除。
#!/bin/bash
#call with params: in_directory out_directory
in_directory=$1
out_directory=$2
export in_directory
export out_directory
#Duplicate the in_directory folder structure in out_directory
cd "$in_directory" &&
find . -type d -exec mkdir -p -- "$out_directory"/{} \;
find $in_directory -type f -name '*' -exec sh -c '
for file do
#Quite a lot of other stuff, including some fiddling with $file to
#get rel_file, the part of the path to a file from
#in_directory. E.g if in_directory is ./ then file ./ABC/123.txt
#will have rel_file ABC/123.txt
cat $file|tr -d '|' |sed -e 's/,/|/g' > $out_directory/$rel_file
done
' sh {} +
一個問題可能是我如何嘗試寫入文件以將輸出傳遞到。 但是,這不是主要/唯一的問題,因為當我用顯式的測試路徑替換它時,我仍然收到錯誤| sed -e's /,/ | / g'|沒有這樣的文件或目錄,這使我認為cat $ file部分是問題嗎?
任何幫助都一如既往地受到高度贊賞-這只是我必須編寫的第二個BASH腳本,因此我希望我犯了一個相當基本的錯誤!
您的“內部”單引號被視為“外部”單引號,並給您帶來麻煩。 您認為您正在引用|
在tr
命令中,但實際上是在結束以單引號引起來的無引號|
字符串|
然后開始一個新的單引號字符串。 然后,該第二個單引號字符串以您認為正在啟動sed
腳本的單引號結束,而結束了先前的單引號字符串,等等。
如果可以,對那些嵌入的單引號使用雙引號。 在無法執行此操作的地方,您必須使用'\\''
序列在單引號引起來的字符串中獲取文字單引號。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.