我在当前目录中有许多文本文件。每个文件都包含有关电影的数据。每个文件的内容将按照以下格式:
Movie name
Storyline
Director name
Year of release
如何通过shell脚本根据控制器的名称组织文件。由同一导演制作的电影将被移动到以导演命名的文件夹中。我怎么能写shell脚本呢?
答案 0 :(得分:0)
粗略的解决方案将是
for file in *; do
director=$( some code here depending on requirements clarification )
mkdir -p "$director" # quotes are crucial!
# -p suppresses errors if dir already exists.
mv -v "$file" "$director"
done
答案 1 :(得分:0)
假设电影的文件名始终是第一行,而且Director名称始终是倒数第二行。你可以这样做:
#!/bin/bash
MOVIES_DIR=/path/to/your/movies
for FILE in ${MOVIES_DIR}/*.txt; do
# Movie name will always be the first line
MOVIE=$(sed '1q;d' "$FILE")
# Director will always be the next to last line
DIRECTOR=$(tac "$FILE" | sed '2q;d')
# Make the director folder
mkdir -p "${MOVIES_DIR}/${DIRECTOR}"
# Find inside the `MOVIES_DIR` files with the movie name with any extension
# That is NOT .txt and moves them to the proper director folder.
find "${MOVIES_DIR}" -maxdepth 1 -name "${MOVIE}.*" -not -name '*.txt' -print0 |
while IFS= read -r -d '' NAME; do
FILENAME=$(printf '%s\n' "$NAME")
mv "$FILENAME" "${MOVIES_DIR}/${DIRECTOR}"
done
done
我的误解是你想将文本文件中具有相同名称的电影移动到相应的导演文件夹中。我现在看到您打算自己移动 文本 文件。我从您提供的链接下载了所有文本文件,并成功将所有文本文件分类到相应的文件夹中:
#!/bin/bash
MOVIES_DIR=/path/to/your/files
for FILE in ${MOVIES_DIR}/*.txt; do
# I thought the description was on one line, but it looks like it can span
# multiple. So get the next to last line instead, since year is only one line. I also changed this in the first script.
DIRECTOR=$(tac "$FILE" | sed '2q;d')
DIRECTOR_PATH="$MOVIES_DIR/$DIRECTOR"
mkdir -p "$DIRECTOR_PATH"
# Move the current text file to the Director folder.
mv "$FILE" "$DIRECTOR_PATH"
done
第一个脚本应将所有 电影 排序到导演文件夹中,假设文本文件与电影位于同一目录中。
第二个脚本应将所有 文本 文件排序到相应的Director文件夹中。