1

次のようなコマンドの結果を1つずつ取得するにはどうすればよいですか

# locate file.txt
/home/alex/file.txt
/backup/file.txt

私がやりたいことは、対話型のスクリプトを作成してどこに質問するかです:Which of the following files would you like to copy/recover? [1],[2]:

例:

filetorecover.txt
_________________
   file.txt
   file1.txt
   ...

./recover filestorecover.txt /home/alex/data/
file.txt could not be located at /home/alex/data, but it was locate here:
[1] /home/alex/files/
[2] /backup/file.txt
  • filestorecover => は、検索するファイルを含むファイルです
  • /home/alex/files/ => は、検索するメイン フォルダーです。ファイルがそこにない場合は、locate file.txt

したがって、主に、上記で説明したように、後で使用するために、検索または検索からこれらの X の結果を 1 つずつ取得する方法を探しています。

アップデート

find/locate の結果の最も一般的なパスを確認することはできますか? つまり、設定したいファイルが 6 つと/backup/2 つある/home/alex/files/場合、または最も一般的なフォルダーからすべてのファイルを取得する方法を尋ねます/backup/

これは、X 個を超えるファイル (例: 10) がある場合を意味します。

4

3 に答える 3

2

bash を使用している場合は、次のような組み込み配列を使用できます。

# Get all the files
files=`find . -name "file.txt"`
# Put them into an array
declare -a afiles
afiles=( ${files} )

# Output filenames
for (( i = 0; i < ${#afiles[@]}; i += 1 ));
do
    printf "[%d] %s\n" ${i} ${afiles[$i]}
done

afiles(宣言は必要ありませんが、配列であるというのは良いコメントです。)

配列を使用すると、ユーザーが で数値を入力した後にファイル名にアクセスできるという利点があります${afiles[${number}]}

于 2012-04-18T09:39:14.317 に答える
1

awk を使用して読み取ります。

# list of files in temp file
choices=$(mktemp -t choices.XXXXX)
find . -name "file.txt") > $choices

# choices with number prefix
cat $choices | awk '{print "[" NR "]" $0}'

# prompt
echo "Choose one"
read num

# find choice
choice=$( cat $choices | awk "{if (NR==$num){print \$0}}" )
echo "You choose $choice"
于 2012-04-18T09:45:01.780 に答える
1

あなたの更新のために

#paths in order
find . -name '*.txt' | awk '{gsub(/\/[^/]*$/,"");path[$0]+=1} END {for (i in path) print path[i]" "i}' | sort -rg | cut -d ' ' -f 2

残りはすでに投稿されているものを使用してください

于 2012-04-18T11:31:00.110 に答える