【问题标题】:Use sed find ID in txt file and use ID to rename file使用 sed 在 txt 文件中查找 ID 并使用 ID 重命名文件
【发布时间】:2018-03-28 10:13:19
【问题描述】:

使用 wget,将网页下载为 .txt 文件。保存的这个文件使用网页的部分 url 命名,例如。 wget http://www.example.com/page/12345/ -O 12345.txt,为方便起见。

我正在从 shell 脚本 .sh 文件运行命令,因为它可以执行多个命令,一次一行,例如。

下载文件后,我使用 sed 解析我想要保留的文本/字符。我想要的部分文字包括blah blah Product ID a5678

我想要的是使用 sed 找到 a5678 并使用它将文件 12345.txt 重命名为 a5678.txt。

# script.sh
wget http://www.example.com/page/12345/ -O 12345.txt
sed -i '' 's/pattern/replace/g' 12345.txt
sed command to find a5678 # in line blah blah Product ID a5678 
some more sed commands
mv 12345.txt a5678.txt (or use a variable $var.txt)?

我该怎么做?

我可能还想使用相同的 ID a5678 并创建一个同名的文件夹 a5678。因此 .txt 文件位于文件夹中,就像/a5678/a5678.txt

mkdir a5678 (or mkdir $var)? && cd a5678

我已经搜索了半天的答案,但找不到任何答案。我找到的最接近的是 Find instance of word in files and change it to the filename 但这与我想要的完全相反。我也考虑过使用变量,例如。 https://askubuntu.com/questions/76808/how-do-i-use-variables-in-a-sed-command 但我不知道如何将找到的字符保存为变量。

非常期待一些帮助!谢谢!我在运行 Sierra 的 Mac 上。

【问题讨论】:

  • 除非您在文件中 替换 字符,否则我可能只使用 grep 代替,剪切结果以提取重命名所需的字符串。或者切换到 perl...

标签: bash macos shell sed wget


【解决方案1】:

试图最小化,所以要符合你的逻辑。

in=12345.txt
out=$( grep ' Product ID ' $in | sed 's/.* Product ID \([^ ]*\) .*/\1/' )
mkdir -p $out
mv $in $out/$out.txt

【讨论】:

  • 我可能会建议几个模组:在grep 中添加一个-m 1 标志(以防止多次匹配),并在mkdirmv 周围添加一个if [ $out ]; then 子句命令,所以如果没有找到字符串,你不会得到奇怪的行为。
【解决方案2】:

谢谢大家!在您的启发下,我通过(不使用 grep)解决了我的问题:

in=12345
out=$(sed -n '/pattern/ s/.*ID *//p' $in.txt)
mv $in.txt $out.txt
cd ..
mv $in $out

【讨论】:

  • 我想我终于找到了-n - /p 组合,哈哈。谢谢。 :)
猜你喜欢
  • 2014-02-10
  • 2021-02-22
  • 2015-11-02
  • 2011-01-23
  • 2011-08-06
  • 2013-06-12
  • 1970-01-01
  • 1970-01-01
  • 2021-09-29
相关资源
最近更新 更多