简体   繁体   English

Bash重命名文件基于从另一个文件打印的行

[英]Bash rename file based on line printed from another file

I have downloaded a series of files from https://www.grc.com/securitynow.htm which is a podcast. 我已经从https://www.grc.com/securitynow.htm下载了一系列文件,这是一个播客。 I downloaded 2 files per podcast. 我每个播客下载了2个文件。

File 1 is named sn-471.mp3 (I have 471 of these named sequentially) File 2 is named sn-471.txt (I have 471 of these named sequentially) 文件1名为sn-471.mp3(我依次命名为471)文件2命名为sn-471.txt(我依次命名为471)

What I am trying to do is this, I am printing the 6th line of the file, and cutting from the 2nd delimiter to the end of line with this: 我要这样做的是,我正在打印文件的第六行,并从第二个定界符切到此行的末尾:

sed -n 6p sn-471.txt | cut -f2-

That is working perfectly right now. 现在,这非常正常。 The reason for the 6th line is so far in my test, the 6th line is always the TITLE: and then a tab then the title of the episode. 到目前为止,第六行的原因在我的测试中,第六行始终是TITLE:然后是选项卡,然后是剧集的标题。 I assume that if i run into the issue where the 6th line is not always the title, then I can grep for TITLE: then use the same cut. 我假设如果遇到第6行并不总是标题的问题,那么我可以grep代表TITLE:然后使用相同的剪切。

With the above I am able to print the Title of the episode. 通过以上操作,我可以打印剧集的标题。 What I'm trying to do and cant seem to wrap my head around is use this data to then rename the mp3 file. 我正在尝试做的并且似乎无法解决的问题是使用此数据来重命名mp3文件。

So far I have come up with this, but its not working. 到目前为止,我已经提出了这个建议,但是它没有用。

#/bin/bash
for i in 
  sn-471.txt;                                                                          
do
  X=$(sed -n 6p $i | cut -f2-)
  mv $i `${X}`.txt
done

I understand that i will need to make the "sn-471.txt" part something like "sn-*.txt" soon, but for this test this is what I have been using. 我知道我很快将需要使“ sn-471.txt”部分类似于“ sn-*。txt”,但是对于此测试,这是我一直在使用的。 If this has been covered already, I haven't been able to find it so far via various Google searches. 如果已经解决了这个问题,那么到目前为止,我还无法通过各种Google搜索找到它。

Thank all of you for any help you provide! 感谢您提供的任何帮助!

You can store the ouput of the sed command to a variable with command substitution. 您可以使用命令替换将sed命令的输出存储到变量中。 You can then use parameter expansion to remove the ".txt" extension: 然后,您可以使用参数扩展来删除“ .txt”扩展名:

for file in sn-*.txt ; do
    title=$( sed -n 6p "$file" | cut -f2- )
    mv "${file%txt}"mp3 "$title".mp3
done

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM