【问题标题】:How to copy filename up to specific characters (and add the copied text to the top of the same file)如何将文件名复制到特定字符(并将复制的文本添加到同一文件的顶部)
【发布时间】:2021-04-29 20:27:23
【问题描述】:

我正在更新一个 bash 脚本(适用于 Mac),我已经有一段时间没看过了,我想将文件名的字符复制到 __(两个下划线)。我目前抓取的前 6 个字符,并很好地粘贴,但我不确定如何更改它以将所有内容复制到前两个下划线(不是 _ 或单个下划线)。

#This copies the first 6 characters of the FILENAME 
#and adds it to the top of the same file
#!/bin/bash
for filename in ./*.txt
do
    text="${filename:2:6}"
    echo $text | cat - $filename > temp && mv temp $filename;
done;

提前感谢您的帮助:)

【问题讨论】:

  • .bat 不是 OSX 脚本它是 Windows 脚本

标签: bash macos filenames


【解决方案1】:

请您尝试以下方法:

text=$(sed 's/__.*/__/' <<< "$filename")
  • __.* 匹配 $filename 中的前两个下划线和以下字符
  • 然后s 命令将上面的子字符串替换为两个下划线。

顺便说一句,请记住在后续行中用双引号将变量名 $text$filename 括起来。

【讨论】:

  • 非常好 - 谢谢!通过一个小小的调整,它对我来说非常有效。我更改了第二个“__”参考。空白以将其删除并在“文件名”之后添加:2以修剪“./”它在结果中添加......可能是路径名的东西。再次感谢! :)
【解决方案2】:

您正在使用 Bash,它为此提供了一个特殊的替换 %%

#!/bin/bash
for filename in *.txt
do
    text="${filename%%__*}"     # Remove "__" and anything that follows
    echo $text | cat - $filename > temp && mv temp $filename;
done

(请注意,我在您的脚本中将./*.txt 替换为*.txt

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-20
    • 2014-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-17
    • 1970-01-01
    相关资源
    最近更新 更多