问题:在文件顶部用父目录的基本名称标记文件。
即,对于
/mnt/Vancouver/Programming/file1
用Programming标记file1的顶部。
解决方案 1 -- 非空文件:
bn=${PWD##*/} ## bn: basename
sed -i '1s/^/'"$bn"'\n/' <file>
1s 将文本放在文件的第 1 行。
解决方案 2 -- 空文件或非空文件:
上面的sed 命令在处理空文件时失败。这是一个解决方案,基于https://superuser.com/questions/246837/how-do-i-add-text-to-the-beginning-of-a-file-in-bash/246841#246841
printf "${PWD##*/}\n" | cat - <file> > temp && mv -f temp <file>
请注意,cat 命令中的- 是必需的(读取标准输入:有关更多信息,请参阅man cat)。在这里,我相信,需要将 printf 语句的输出(到 STDIN),并将该文件和文件放入 temp ... 另见 http://www.linfo.org/cat.html 底部的解释。
我还在mv 命令中添加了-f,以避免在覆盖文件时被要求确认。
递归目录:
for file in *; do printf "${PWD##*/}\n" | cat - $file > temp && mv -f temp $file; done
还要注意,这会用空格分隔路径;在其他地方有解决方案(例如文件通配,或 find . -type f ... 类型的解决方案)。
ADDENDUM: Re:我的最后一条评论,此脚本将允许您递归遍历路径中带有空格的目录:
#!/bin/bash
## https://stackoverflow.com/questions/4638874/how-to-loop-through-a-directory-recursively-to-delete-files-with-certain-extensi
## To allow spaces in filenames,
## at the top of the script include: IFS=$'\n'; set -f
## at the end of the script include: unset IFS; set +f
IFS=$'\n'; set -f
# ----------------------------------------------------------------------------
# SET PATHS:
IN="/mnt/Vancouver/Programming/data/claws-test/corpus test/"
# https://superuser.com/questions/716001/how-can-i-get-files-with-numeric-names-using-ls-command
# FILES=$(find $IN -type f -regex ".*/[0-9]*") ## recursive; numeric filenames only
FILES=$(find $IN -type f -regex ".*/[0-9 ]*") ## recursive; numeric filenames only (may include spaces)
# echo '$FILES:' ## single-quoted, (literally) prints: $FILES:
# echo "$FILES" ## double-quoted, prints path/, filename (one per line)
# ----------------------------------------------------------------------------
# MAIN LOOP:
for f in $FILES
do
# Tag top of file with basename of current dir:
printf "[top] Tag: ${PWD##*/}\n\n" | cat - $f > temp && mv -f temp $f
# Tag bottom of file with basename of current dir:
printf "\n[bottom] Tag: ${PWD##*/}\n" >> $f
done
unset IFS; set +f