
您好,我目前正在嘗試執行以下程式碼。我在變數 DATE 中儲存了一個字串,其格式為 YYYY/MM/DD。我嘗試使用 cut 命令提取年份。我收到一條錯誤訊息,指出它不是檔案或目錄。我可以進行修改或採取不同的方法嗎?
for file in ~/filesToSort/*
do
DATE=$(head -1 $file | tr "-" "/")
echo "${DATE}"
YYYY=$(cut -c1-4 accounts $DATE)
#echo "${YYYY}"
done
謝謝
答案1
該cut
實用程式從其標準輸入流讀取數據,它不會對作為參數給出的字串進行操作。
因此,要使用cut
,您需要在標準輸入上傳遞資料:
YYYY=$( printf '%s\n' "$DATE" | cut -d '/' -f 1 )
然而,這在循環中會非常慢。相反,使用內建參數替換來刪除字串/
中第一個之後的所有內容$DATE
:
YYYY=${DATE%%/*}
$DATE
這會刪除與shell 模式相符的最長後綴字串/*
。如果字串是2021/10/21
,則傳回2021
。
取得目錄中每個文件的前四個字元(這是我的本質相信您當前的程式碼正在嘗試執行此操作),您可以sed
像這樣使用:
for name in "$HOME"/filesToSort/*; do
sed -e 's/\(....\).*/\1/' -e q "$name"
done
這會讀取每個檔案的第一行,用該行的前四個字元替換該行的內容,然後將結果輸出到終端後退出。
答案2
如果您的 shell 支持,您可以使用 Here Strings ( <<<
) 來實現此目的。從man bash
:
Here Strings
A variant of here documents, the format is:
[n]<<<word
The word undergoes tilde expansion, parameter and variable expansion,
command substitution, arithmetic expansion, and quote removal. Path‐
name expansion and word splitting are not performed. The result is
supplied as a single string, with a newline appended, to the command
on its standard input (or file descriptor n if n is specified).
在你的情況下,你會這樣做:
for file in ~/filesToSort/*
do
date=$(head -1 "$file" | tr "-" "/")
echo "${DATE}"
yyy=$(cut -c1-4 <<< "$date")
echo "$yyy"
done
答案3
使用好 ole 的另一種方法awk
for file in *; do
awk -F'-' 'NR==1 {print $1}' $file
done
-F '-'
告訴 awk 使用 the-
作為分隔符NR==1
告訴 awk 僅讀取每個檔案的第一行{print $1}
只列印由分隔符號分隔的第一個字段